Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between HashSet and Set?

Saw the code snippet like

Set<Record> instances = new HashSet<Record>(); 

I am wondering if Hashset is a special kind of set. Any difference between them?

like image 849
user496949 Avatar asked Feb 28 '11 08:02

user496949


People also ask

What is difference between HashSet and set?

A Set is a generic set of values with no duplicate elements. A TreeSet is a set where the elements are sorted. A HashSet is a set where the elements are not sorted or ordered.

What is tree set and HashSet?

Hash set and tree set both belong to the collection framework. HashSet is the implementation of the Set interface whereas Tree set implements sorted set. Tree set is backed by TreeMap while HashSet is backed by a hashmap. Sr.

Which is better HashSet or TreeSet?

Simply put, HashSet is faster than the TreeSet. HashSet provides constant-time performance for most operations like add(), remove() and contains(), versus the log(n) time offered by the TreeSet.


2 Answers

A Set represents a generic "set of values". A TreeSet is a set where the elements are sorted (and thus ordered), a HashSet is a set where the elements are not sorted or ordered.

A HashSet is typically a lot faster than a TreeSet.

A TreeSet is typically implemented as a red-black tree (See http://en.wikipedia.org/wiki/Red-black_tree - I've not validated the actual implementation of sun/oracle's TreeSet), whereas a HashSet uses Object.hashCode() to create an index in an array. Access time for a red-black tree is O(log(n)) whereas access time for a HashSet ranges from constant-time to the worst case (every item has the same hashCode) where you can have a linear search time O(n).

like image 142
Erik Avatar answered Oct 21 '22 04:10

Erik


The HashSet is an implementation of a Set.

like image 33
vaugham Avatar answered Oct 21 '22 06:10

vaugham