Search code examples
javaobjecthashmaphashsethashcode

How can I take into consideration the object itself when calculating a hash for an object in Java?


I was working on some algorithmic problems when I got to this and it seemed interesting to me. If I have two lists (so two different objects), with the same values, the hashcode is the same. After some reading, I understand that this is how it should behave. For example:

        List<String> lst1 = new LinkedList<>(Arrays.asList("str1", "str2"));
        List<String> lst2 = new LinkedList<>(Arrays.asList("str1", "str2"));
        System.out.println(lst1.hashCode() + " " + lst2.hashCode());
        ...........
        Result: 2640541 2640541

My purpose would be to differentiate between lst1 and lst2 in a list for example.

Is there a structure (like a HashSet for example) that takes into consideration the actual object and not only the values inside the object when calculating the hashcode for something?


Solution

  • Yes, you can use java's java.util.IdentityHashMap, or guava's identity hash set.

    The hashes of the two lists must be equal, because the objects are equal. But the identity map and set above are based on the identity of the list objects, not their hash.