Thursday 19 June 2014

Why set interface doesn't allows duplicates in java?

       If you are having 3+ yrs Of experience then some interviewer will ask this question. Actually interviewer will test for how set internally works in java.
    
       Internally SET store element using HashMap . HashMap is a structure of Key value pairs, but in set there is no key and value pair. Here what the values passed by the Set is treated as Keys of HashMap Internally. As we know that keys are unique cannot be duplicated. HashMap value as constant every time. That is the reason if you pass any duplicate value it return false and does not added to the Set.
       If the adding element return true it will added into Set Else it return False, that why it won't give any compilation or run time error and it wont be added to Set




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: