HashMap, Hashtable, IdentityHashMap in Java

Why is HashMap needed if there is a Hashtable?

  • The methods of the Hashtable class are synchronized, which leads to a performance hit, but the HashMap is not;
  • Hashtable cannot contain null elements, whereas a HashMap can contain one null key and any number of null values;
  • Iterator for HashMap, unlike Enumeration for Hashtable, works on the "fail-fast" principle (throws an exception in case of any data inconsistency).

Hashtable is a deprecated class.

Difference between HashMap and IdentityHashMap

IdentityHashMap is a data structure that also implements the Map interface and uses reference comparison when comparing keys (values), rather than calling the equals() method. In other words, in IdentityHashMap, two keys k1 and k2 will be considered equal if they point to the same object, i.e. the condition k1 == k2 is satisfied.

IdentityHashMap does not use the hashCode() method, instead of which the System.identityHashCode() method is used, for this reason IdentityHashMap has better performance compared to HashMap, especially if the latter stores objects with expensive equals() and hashCode() methods.

One of the main requirements for using HashMap is key immutability. IdentityHashMap does not use equals() and hashCode() methods, this rule does not apply to it.

IdentityHashMap can be used to implement serialization/cloning. When executing such algorithms, the program needs to maintain a hash table with all references to objects that have already been processed. Such a structure should not treat unique objects as equal, even if the equals() method returns true.


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed