Saturday 22 April 2017

Set

1. What is a Set?

Answer: Set is an unordered collection which does not maintain the insertion order unlike list.
Set doesn't allow the duplicate values unlike List. If you try to add same value again it will replace the old with new value.
Example: 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class SetExample {
 public static void main(String[] args) {
   // 1. Instantiated Set
   Set<Integer> mySet = new HashSet<Integer>();

   // 2. Adding elements to Set
   mySet.add(1);
   mySet.add(2);
   mySet.add(3);
   mySet.add(4);
   mySet.add(5);
   mySet.add(4);
   mySet.add(5);
   mySet.add(4);
   
   // 3. Iterating over Set
   Iterator<Integer> iterator = mySet.iterator();
   while (iterator.hasNext()) {
    System.out.println(iterator.next());
   }
 }
}
You can see above code is more like the code that we have for List as both implements java.utill.Collection interface. Methods  like add(), remove() etc. are declare in Collection interface only. 
In above code we are trying to add Integer value "4" 3 times and Integer value "5" 2 times. But in console you will get both these value printed only once as Set doesn't allow duplicate values.

2. What is underlying Data structure of Set?

AnswerSet doesn't implement any specific data structure directly instead it uses Map collection. 
Map is collection which based on the concept of Key-Value pair. So whenever you create an instance of Set, It internally creates and manages a instance of Map to store the values. Whenever you call add(value) method of Set, It internally make calls to Map's put(key, value) method and uses value need to be added in set as Key parameter and passes an empty instance of Object class as value parameter.
Example: Assume you want to add 3 in Set, then you will call() add method as below.
mySet.add(3);, Now Set's add() method will make call to Map's put() method as "map.put(3, new Object());".


3. Explain Set class Hierarchy?

AnswerClass hierarchy of Set is as follows:
Fig: Set class Hierarchy.

Set has following three implementations:
1. HashSet : It is considered as default implementation of Set. It uses HashMap internally. It doesn't maintain the insertion order as It is default implementation of Set.  
2. LinkedHashSet : It has all the behavior of Set except it maintains the insertion order as It uses LinkedHasMap internally.
3. TreeSet : It has all the behavior of Set except it store the values in sorted order. It uses as TreeMap internally.

4. Explain the situations when you will use List and Set?

Answer Which collection we should use, It all depends on your requirements. So in order to pick right collection you should have clear picture of your requirement. Let's discuss which collection fit where:
1. List :We should use List when your requirements required to maintain insertion order and you can or can not have duplicate values.
2. Set(HashSet) : Set Should be use when your requirement says that you can not have duplicate values and maintaining insertion order is not required.
3. LinkedHashSet : It should be use when your requirement says that you can not have duplicates values but you need to maintain insertion order.
4. TreeSet : It should be use when your requirement says that you can not have duplicates values but you need to maintain sorting order.


5. What will be the output of below program?


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetExample {
 public static void main(String[] args) {
   Set<Object> mySet = new TreeSet<Object>(); //Hint : TreeSet maintains sorting order, 
           //TreeSet sorts the data after every insertion and deletion.
   mySet.add(new Integer(2));
   mySet.add(3);
   mySet.add("Hello");

   Iterator<Object> iterator = mySet.iterator();
   while (iterator.hasNext()) {
    System.out.println(iterator.next());
   }
 }
}
Answer Runtime Exception, It will throw ClassCastException at line number 11.
Since you have created mySet of type Object then It should allow String as well. Then why it throws Runtime exception?
It is because TreeSet uses Comparable to sort the values, Since you already have value of type Integer and you trying to insert value of type String. When you try to enter "Hello" at line number 11, Set will invoke the compareTo() method of  String class (which takes String as input) and will pass integer value to as parameter in order to decide sorting order. And here we will get ClassCastException saying that Integer can not be cast to String.

No comments:

Post a Comment