Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashSet vs TreeSet vs LinkedHashSet on basis of adding duplicate value

I am learning heart of core java i.e. Collections. I would like to know what happens internally when we add duplicate element in HashSet, TreeSet, LinkedHashSet.

Whether entry is replaced, ignored or exception is thrown and program terminates. And one sub question is, Which one has same or average time complexity for all its operations

Your response will be greatly appreciated.

like image 551
Prashant Shilimkar Avatar asked Nov 21 '13 09:11

Prashant Shilimkar


People also ask

Does LinkedHashSet allow duplicates?

Duplicate values are not allowed in LinkedHashSet. One NULL element is allowed in LinkedHashSet. It is an ordered collection which is the order in which elements were inserted into the set (insertion-order).

What are the differences between HashSet LinkedHashSet and TreeSet?

HashSet: If you don't want to maintain insertion order but want to store unique objects. LinkedHashSet: If you want to maintain the insertion order of elements then you can use LinkedHashSet. TreeSet: If you want to sort the elements according to some Comparator then use TreeSet.

What is the advantage of LinkedHashSet over HashSet?

HashSet is an unordered & unsorted collection of the data set, whereas the LinkedHashSet is an ordered and sorted collection of HashSet. HashSet does not provide any method to maintain the insertion order. Comparatively, LinkedHashSet maintains the insertion order of the elements.


1 Answers

TreeSet, LinkedHashSet and HashSet in Java are three Set implementation in collection framework and like many others they are also used to store objects. Main feature of TreeSet is sorting, LinkedHashSet is insertion order and HashSet is just general purpose collection for storing object. HashSet is implemented using HashMap in Java while TreeSet is implemented using TreeMap. TreeSet is a SortedSet implementation which allows it to keep elements in the sorted order defined by either Comparable or Comparator interface. Comparable is used for natural order sorting and Comparator for custom order sorting of objects, which can be provided while creating instance of TreeSet. Anyway before seeing difference between TreeSet, LinkedHashSet and HashSet, let's see some similarities between them:

1) Duplicates : All three implements Set interface means they are not allowed to store duplicates.

2) Thread safety : HashSet, TreeSet and LinkedHashSet are not thread-safe, if you use them in multi-threading environment where at least one Thread modifies Set you need to externally synchronize them.

3) Fail-Fast Iterator : Iterator returned by TreeSet, LinkedHashSet and HashSet are fail-fast Iterator. i.e. If Iterator is modified after its creation by any way other than Iterators remove() method, it will throw ConcurrentModificationException with best of effort. read more about fail-fast vs fail-safe Iterator here

Now let’s see difference between HashSet, LinkedHashSet and TreeSet in Java :

Performance and Speed : First difference between them comes in terms of speed. HashSet is fastest, LinkedHashSet is second on performance or almost similar to HashSet but TreeSet is bit slower because of sorting operation it needs to perform on each insertion. TreeSet provides guaranteed O(log(n)) time for common operations like add, remove and contains, while HashSet and LinkedHashSet offer constant time performance e.g. O(1) for add, contains and remove given hash function uniformly distribute elements in bucket.

Ordering : HashSet does not maintain any order while LinkedHashSet maintains insertion order of elements much like List interface and TreeSet maintains sorting order or elements.

Internal Implementation : HashSet is backed by an HashMap instance, LinkedHashSet is implemented using HashSet and LinkedList while TreeSet is backed up by NavigableMap in Java and by default it uses TreeMap.

null : Both HashSet and LinkedHashSet allows null but TreeSet doesn't allow null and throw java.lang.NullPointerException when you will insert null into TreeSet. Since TreeSet uses compareTo() method of respective elements to compare them which throws NullPointerException while comparing with null, here is an example:

TreeSet cities Exception in thread "main" java.lang.NullPointerException         at java.lang.String.compareTo(String.java:1167)         at java.lang.String.compareTo(String.java:92)         at java.util.TreeMap.put(TreeMap.java:545)         at java.util.TreeSet.add(TreeSet.java:238) 

Comparison : HashSet and LinkedHashSet uses equals() method in Java for comparison but TreeSet uses compareTo() method for maintaining ordering. That's why compareTo() should be consistent to equals in Java. failing to do so break general contact of Set interface i.e. it can permit duplicates.

Use can use below link to see internal implementation http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/HashSet.java#HashSet.add%28java.lang.Object%29

From the source code  Hashset hases Hashmap to store the data and LinkedHashSet extends Hashset and hence uses same add method of Hashset But TreeSet uses NavigableMap to store the data 

Source: http://javarevisited.blogspot.com/2012/11/difference-between-treeset-hashset-vs-linkedhashset-java.html#ixzz2lGo6Y9mm

like image 162
constantlearner Avatar answered Sep 20 '22 23:09

constantlearner