Thursday, 19 June 2014

Why Doesn't the Set Interface Allow Duplicate Elements in Java?

       If you have 3+ years of Java experience, an interviewer may ask this question to test your understanding of how a Set works internally in Java.

Internally, a HashSet stores its elements using a HashMap. A HashMap stores data as key-value pairs, whereas a Set contains only unique elements. When an element is added to a HashSet, it is stored as the key in the underlying HashMap, and a constant dummy object is used as the value for every entry.

Since HashMap does not allow duplicate keys, HashSet also does not allow duplicate elements. If you attempt to add a duplicate element, the add() method returns false, and the element is not added to the Set.

When a new element is added successfully, the add() method returns true. If the element already exists, it returns false. Therefore, adding a duplicate element does not result in a compile-time or runtime error—it is simply ignored.



Related Posts:--
1) How HashMap works internally in Java?
2) Internal Implementation of TreeMap in Java
3) Internal implementation of ArrayList in Java
4) Collection Interview Questions and Answers in Java
5) Internal Implementation of LinkedList in Java
6) Collection Hierarchy in Java

2 comments: