Crigges
Crigges

Reputation: 1243

Use Strings as key in IdentityHashMap

I got a simple IdentityHashmap:

IdentityHashmap<String, Integer> map;

Now i want to use Strings as keys. The main issue is the java string pool:

String a = "Hello";
String b = "Hello";
map.put(a, 1);
map.put(b, 2);
System.out.println(map.get(a)) //Prints "2" since a == b

I know i could avoid this problem by using new String("Hello") instead of "Hello" but i get the String as parameter and since i can't force the user to use the new constructor i have no idea how to solve this problem.

Upvotes: 1

Views: 332

Answers (1)

candied_orange
candied_orange

Reputation: 7354

I use it in some serialization system. Which allows the user to save and delete objects without rewriting the whole file by using: File.save(Object o) File.delete(Object o) If some object is equals to some other they still need to get stored separately

In this case you want neither value nor identity. At least not heap identity which is what == gives you. You want file offset identity. You're trying to violate a design principle. You should never try to force one property to mean two things. You need another property. Either force the user to delete objects using a structure that couples their heap reference with their file offset location or wrap all objects in something that will have the file location.

Upvotes: 3

Related Questions