Reputation: 86135
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?
Upvotes: 112
Views: 147782
Reputation: 1
**
** It is an interface which is a subtype of Collection interface, just like LIST and QUEUE.
Set has below 3 subclasses, it is used to store multiple objects without duplicates.
**
**
Can use one NULL value(as Duplicate is not allowed), data is stored randomly as it does not maintain sequence.
Upvotes: -1
Reputation: 361
HashSet is a class derived from Set interface. As a derived class of Set, the HashSet attains the properties of Set. Important and the most frequently used derived classes of Set are HashSet and TreeSet.
Upvotes: 1
Reputation: 28578
The question has been answered, but I haven't seen the answer to why the code mentions both types in the same code.
Typically, you want to code against interfaces which in this case is Set. Why? Because if you reference your object through interfaces always (except the new HashSet()) then it is trivial to change the implementation of the object later if you find it would be better to do so because you've only mentioned it once in your code base (where you did new HashSet()).
Upvotes: 21
Reputation: 91270
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)
.
Upvotes: 141
Reputation: 13676
Set is a parent interface of all set classes like TreeSet, LinkedHashSet etc.
HashSet is a class implementing Set interface.
Upvotes: 5
Reputation: 437
Set is the general interface to a set-like collection, while HashSet is a specific implementation of the Set interface (which uses hash codes, hence the name).
Upvotes: 12