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 :
In short, we can say that set is a wrapper of Map with a contract associated with it.
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
extends AbstractSet
implements Set, Cloneable, java.io.Serializable
{
private transient HashMap map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public HashSet() {
map = new HashMap<>();
}
// some code here
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
// some code here
}
In this implementation, java defined a transient variable map which is being used for all the operations of Set. When we add an element to set, the map's put method is called internally and got added to the map with default value PRESENT. Same for iterator, when we call iterator over the collection, it returns the iterator of keys of this map.extends AbstractSet
implements Set
{
private transient HashMap
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public HashSet() {
map = new HashMap<>();
}
// some code here
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
// some code here
}
public Iterator iterator() {
return map.keySet().iterator();
}
return map.keySet().iterator();
}
In short, we can say that set is a wrapper of Map with a contract associated with it.
Look at my other posts:
Some other interesting blogs:
Comments
Post a Comment