Use cases for IdentityHashMap

后端 未结 7 708
谎友^
谎友^ 2020-12-12 13:31

Could anyone please tell what are the important use cases of IdentityHashMap?

7条回答
  •  暖寄归人
    2020-12-12 14:12

    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: EnumMap
    • Class objects. They are also comparable by reference.
    • Interned Strings. Either by specifying them as literals or calling String.intern() on them.
    • Cached instances. Some classes provide caching of their instances. For example quoting from the javadoc of Integer.valueOf(int):

      This method will always cache values in the range -128 to 127, inclusive...

    • Certain libraries/frameworks will manage exactly one instance of ceratin types, for example Spring beans.
    • Singleton types. If you use istances of types that are built with the Singleton pattern, you can also be sure that (at the most) one instance exists from them and therefore reference equality test will qualify for equality test.
    • Any other type where you explicitly take care of using only the same references for accessing values that were used to putting values into the map.


    To demonstrate the last point:

    Map 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));
    

    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
    

提交回复
热议问题