Tuesday 3 November 2015

Difference between HashSet and TreeSet

Difference between HashSet and TreeSet


HashSet
TreeSet

Ordering

Stores the object in random order.
There is no guarantee to output as insertion order.

Elements are sorted according to the natural ordering of its elements in TreeSet.

We can use comparator to sort the elements.


Null value

HashSet can store null object.

Storing the null object in TreeSet object, it will throw NullPointer Exception.

Performance

HashSet take constant time performance for the basic operations like add, remove contains and  size.

TreeSet guarantees log(n) time cost for the basic operations (add,remove,contains).

Speed

HashSet is much faster than TreeSet, as time complexity  of HashSet is constant.

Iteration performance of HashSet mainly depends on the load factor and initial capacity parameters.

Slow because most of operation in log(n) time complexity.

(add,remove, contains and size).


Internal implementation

HashSet are internally backed by hashmap.

TreeSet is backed by a  Navigable  TreeMap.


Functionality


Methods pollFirst(), pollLast(), first(), last(), ceiling(), lower() etc. makes TreeSet rich in functionality.

Comparision

HashSet uses equals() method for comparison in java.

TreeSet uses compareTo() method for maintaining ordering.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...