Posts

Showing posts from May, 2017

Set Interface in Java

    In collection framework "Set" is an interface which has all the collection's methods with a contract of having only unique elements. It means if you want to save the n elements and m elements are duplicate out of them then set interface would contain only (n-m) elements and reject m elements during addition to the collection. Set can contain at most one null element. Output: Original Set :: [1, 2, 3] After Insertion test :: [1, 2, 3, 4]     Internally Set uses the hashmap while storing the elements. It has one static object declared which is used as value for this map. Whichever element we add in Set it adds it in the hashmap as a key. If the key is already present map returns the value of that key otherwise it returns null. So if we are getting the null from map, it means the value got added successfully. This property is used in the add method of Set. If we see the HashSet implementation we find the code like : public class HashSet ...