HashSet Vs TreeSet :
- First major difference between HashSet and TreeSet is performance. HashSet is faster than TreeSet.
- In HashSet and TreeSet the HashSet allows null object but TreeSet doesn't allow null Object and throw NullPointerException, Why, because TreeSet uses compareTo() method to compare keys and compareTo() will throw java.lang.NullPointerException.
- HashSet is backed by HashMap while TreeSetis backed by TreeMap.
- HashSet uses equals() method to compare two object in Set and for detecting duplicates while TreeSet uses compareTo() method for same purpose.
- HashSet doesn't guaranteed any order while TreeSet maintains objects in natural Sorted order or the Order defined by either Comparable or Comparator method in Java.
Important*-The TreeSet allows NULL object while it is Empty. If it is not empty then only it doesn't allows NULL Object.
HashSet. |
TreeSet. |
Faster. |
Slower(when compared to HashSet). |
Doesn't Guaranteed Any Order. |
Natural Sorted Order or Order Provided by the Comparable/Comparator. |
Uses equals() method to compare elements. |
Uses compareTo() method to compare elements. |
backed by HashMap. |
backed by TreeMap. |
0 comments:
Post a Comment