Wednesday, July 16, 2014

HashSet vs TreeSet

HashSet

TreeSet

Hash set allow null object
HashSet<String> hs =new HashSet<String>();
 hs.add(null) //runs fine


Tress set will not allow null object .if you try to add null value it will be throw null pointer exception
TreeSet<String> ts =new TreeSet<String>();
 ts.add(null) //throw null pointer exception

class offers constant time performance for the basic operations (add, remove, contains and size).
guarantees log(n) time cost for the basic operations (add, remove and contains)
it does not guarantee that the order of elements will remain constant over time
guarantees that elements of set will be sorted (ascending, natural, or the one specified by you via its constructor)
iteration performance depends on the initial capacity and the load factor of the HashSet.
doesn't offer any tuning parameters for iteration performance
It's quite safe to accept default load factor but you may want to specify an initial capacity that's about twice the size to which you expect the set to grow.
offers a few handy methods to deal with the ordered set like first(), last(), headSet(), and tailSet() etc



Important points:
·         Both guarantee duplicate-free collection of elements
·         It is generally faster to add elements to the HashSet and then convert the collection to a TreeSet for a duplicate-free sorted traversal.
·         None of these implementation are synchronized. That is if multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.

·         LinkedHashSet is in some sense intermediate between HashSet and TreeSet. Implemented as a hash table with a linked list running through it, however it provides insertion-ordered iteration which is not same as sorted traversal guaranteed by TreeSet.

No comments:

Post a Comment