Could anyone please tell what are the important use cases of IdentityHashMap?
You can also use the IdentityHashMap as a general purpose map if you can make sure the objects you use as keys will be equal if and only if their references are equal.
To what gain? Obviously it will be faster and will use less memory than using implementations like HashMap or TreeMap.
Actually, there are quite a lot of cases when this stands. For example:
Enums. Although for enums there is even a better alternative: EnumMapClass objects. They are also comparable by reference.Strings. Either by specifying them as literals or calling String.intern() on them.This method will always cache values in the range -128 to 127, inclusive...
To demonstrate the last point:
Map
Output will be, as expected (because we used the same Object references to query values from the map):
strkey: Key #0
java.lang.Object@1c29bfd: Key #1
1234567: Key #2