Saturday, September 21, 2019

Collection Interview Questions (With Java 8 Enhancements) - Part 3 Set Interface


1. Set Interface - Specialty & Implementations ?

Set is a unique collections of objects.It does not store duplicate objects.

Implementations :  EnumSet, HashSet, LinkedHashSet, TreeSet.

HashSet , backed by a hash table (actually a HashMap instance), is the best performing implementation, but it does not maintain order.
TreeSet is backed by red-black tree and store elements in sorted order.It is slower than HashSet.
LinkedHashSet is backed by HashTable with LinkedList running through it, so it also maintains the order of insertion.

2. Collection operation

Set<String> set =people.stream().filter(x -> x!=null).collect(Collectors.toCollection(TreeSet::new));

3. Can Set Store null values?
You can add null value, but while accessing it will give you Null Pointer Exception. 

Set<String> a1 = new HashSet<>();
Set<String> b1 = new TreeSet<>();
a1.add(null);
b1.add(null);
System.out.println(a1);
System.out.println(b1);

Output :
Exception in thread "main" java.lang.NullPointerException

4. How HashSet store elements?

You must know that HashMap store key-value pairs, with one condition i.e. keys will be unique. HashSet uses Map’s this feature to ensure uniqueness of elements. In HashSet class, a map declaration is as below:
private transient HashMap<E,Object> map;

//This is added as value for each key
private static final Object PRESENT = new Object();
So when you store a element in HashSet, it stores the element as key in map and “PRESENT” object as value. (See declaration above).
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}

5. Can a null element added to a TreeSet or HashSet?

As you see, There is no null check in add() method in previous question. And HashMap also allows one null key, so one “null” is allowed in HashSet.

TreeSet uses the same concept as HashSet for internal logic, but uses NavigableMap for storing the elements.

private transient NavigableMap<E,Object> m;

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
NavigableMap is subtype of SortedMap which does not allow null keys. So essentially, TreeSet also does not support null keys. It will throw NullPointerException if you try to add null element in TreeSet.


No comments:

Post a Comment