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 they 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

2 comments: