-
Notifications
You must be signed in to change notification settings - Fork 1
#QA
Q1 Why does HashSet implementation in Sun Java use HashMap as its backing? In order to reduce Duplication of code and made it Memory Efficient ,HashSet implements HashMap as its backing.
Q2. What copy technique internally used by HashSet clone() method ? There are two copy techniques in every object oriented programming lanuage , deep copy and shallow copy. To create a clone or copy of the Set object, HashSet internally uses shallow copy in clone() method , the elements themselves are not cloned . In other words , a shallow copy is made by copying the reference of the object.
**Q3 ** Why HashSet does not have get(Object o) method ? Most of the people get puzzled by hearing this question . This question tests the deep understanding of the HashSet class .This question helps the interviewer to know whether candidate has the idea about contains() method in HashSet class or not .So let jump to the answer
get(Object o) is useful when we have one information linked to other information just like key value pair found in HashMap .So using get() method on one information we can get the second information or vice-versa.
Unlike HashMap , HashSet is all about having unique values or unique objects . There is no concept of keys in HashSet . The only information we can derive from the HashSet object is whether the element is present in the HashSet Object or not . If the element is not present in the HashSet then add it otherwise return true leaving HashSet object unchanged. Here, contains() method helps to provide this information. Due to the above reason there is no get(Object o) method in HashSet.
Q4 What is the difference between HashSet and TreeSet ? Difference
Q5 What is and when to use Collections.emptySet() . What is the advantage of having emptySet in Collections class ? According to Oracle docs ,Collections.emptySet() returns the empty immutable Set ,not containing null. Advantages of using emptySet() method over creating object using constructor are :
-
Immutable : You should prefer to use immutable collection against the mutable collections wherever possible . It becomes handy as multiple threads accessing the same instance of object will see the same values.
-
Concise : You do not need to manually type out the generic type of the collection - normally it is inferred from the context of the method call.
-
Efficient : As emptySet() method dont create new objects , so they just reuse the existing empty and immutable object . Although ,practically,this trick is not that handy , and rarely improves the performance