You can also use IdentityHashMap as a general-purpose map if , you can make sure that the objects you use as keys will be equal, if and only if their links are equal.
What is the benefit? Obviously, this will be faster and use less memory than using implementations like HashMap or TreeMap .
In fact, there are many things to do when it is worth it. For example:
Enum s. Although there is an even better alternative for listings: EnumMapClass objects. They are also comparable by reference.- Interned
String s. Either pointing them as literals, or by calling String.intern() on them. - Cached Instances. Some classes provide caching of their instances. For example, quoting from javadoc
Integer.valueOf(int) :This method will always cache values ββranging from -128 to 127, inclusive ...
- Some libraries / frameworks will manage exactly one instance of ceratin types, such as Spring beans.
- Singleton types. If you use istances of types that are built using the Singleton template, you can also be sure that one instance exists of them, and therefore the equality test will be qualified for the equality test.
- Any other type in which you explicitly use only the same links to access the values ββthat were used to place the values ββon the map.
To demonstrate the last point:
Map<Object, String> m = new IdentityHashMap<>(); // Any keys, we keep their references Object[] keys = { "strkey", new Object(), new Integer(1234567) }; for (int i = 0; i < keys.length; i++) m.put(keys[i], "Key #" + i); // We query values from map by the same references: for (Object key : keys) System.out.println(key + ": " + m.get(key));
The output will be, as expected (because we used the same Object links to the request values ββfrom the map):
strkey: Key
icza Oct 17 '14 at 8:40 2014-10-17 08:40
source share