HashMap – some interesting facts

HashMap is a Java collection. Here are some interesting facts about it:

  1. It is used to contain a set of unique elements, therefore it does not allow duplicates. But allows 1 null value. Adding an element twice does not result in error. Just the method add returns false instead of true.
  2. It doesn’t have a get method. To obtain an element, use the iterator:

3.  The iteration order is not guaranteed so you won’t be getting A B C all the time

4. In the background it it is backed by a HashMap

5. In the backing HashMap, the element of the set are stored as Keys not as values!

6. HashSet is not synchronized. You can use:

7. HashSet is a fail-fast type of collection. Meaning that it prefers to let the user know of a problem as soon as possible and not be error tolerant. ConcurrentModificationException if an element is removed during iteration, using collection’s own remove method. To prevent this, use iterator’s remove method:

8. The default constructor HashSet() constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).

9. HashSet implements Cloneable meaning that it overrides the clone() method. But this method only does shallow clonning! That is, the containing elements are not cloned.

10. HashSet has a couple of private methods used in serialization / deserialization readObject and writeObject.

11. You can use HashSet to quickly get rid of duplicates that you have in a List:



Leave a Reply

Your email address will not be published. Required fields are marked *