TreeSet, LinkedHashSet and HashSet all are
implementation of Set interface. there are some differences exist between them.
HashSet
|
LinkedHashSet
|
TreeSet
|
||||
How they work internally?
|
HashSet uses HashMap internally to store it’s elements.
|
LinkedHashSet uses LinkedHashMap internally to store it’s
elements.
|
TreeSet uses TreeMap internally to store it’s elements.
|
|||
Order Of Elements
|
HashSet doesn’t maintain any order of elements.
|
LinkedHashSet maintains insertion order of elements. i.e elements are
placed as they are inserted.
|
TreeSet orders the elements according to supplied Comparator. If no
comparator is supplied, elements will be placed in their natural ascending
order.
|
|||
Performance
|
|
|
TreeSet gives less performance
than the HashSet and LinkedHashSet as it has to sort the elements after each
insertion and removal operations.
|
|||
Insertion, Removal And Retrieval Operation
|
|
LinkedHashSet also gives performance of order O(1) for insertion,
removal and retrieval operations.
|
TreeSet gives performance of order
O(log(n)) for insertion, removal and retrieval operations
|
|||
Null elements
|
HashSet allows maximum one null element.
|
LinkedHashSet also allows maximum one null element.
|
TreeSet doesn’t allow even a single null element. If you try to
insert null element into TreeSet, it throws NullPointerException.
|
|||
Memory Occupation
|
HashSet requires less memory than LinkedHashSet and TreeSet as it
uses only HashMap internally to store its elements.
|
LinkedHashSet requires more memory than HashSet as it also maintains
LinkedList along with HashMap to store its elements.
|
TreeSet also requires more memory than HashSet as it also maintains
Comparator to sort the elements along with the TreeMap.
|
|||
|
Use HashSet if you don’t want to maintain any order of elements.
|
|
Use TreeSet if you want to sort
the elements according to some Comparator
|
HashSet Example
HashSet<Dog> dset = new HashSet<Dog>(); dset.add(new Dog(2)); dset.add(new Dog(1)); dset.add(new Dog(3)); dset.add(new Dog(5)); dset.add(new Dog(4)); Iterator<Dog> iterator = dset.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + " "); }
Output:5 3 2 1 4
LinkedHashSet Example
TreeSet Example
|
Output is sorted as follows:Tree set data: 12 34 45 63 |