Java HashMap is a hash table based implementation of Map interface. HashSet is a Set. It creates a collection that uses a hash table for storage. HashMap implements Map, Cloneable, and Serializable interface es.
Storing or Adding mechanism: HashMap internally uses hashing to store or add objects, HashSet internally uses HashMap object to store or add the objects. Speed: HashSet is slower than HashMap. Insertion HashMap uses the put() method for storing data, While in HashSet use add() method for add or storing data.
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.
HashSet internally uses HashMap to store it's elements. Whenever you create a HashSet object, one HashMap object associated with it is also created. This HashMap object is used to store the elements you enter in the HashSet. The elements you add into HashSet are stored as keys of this HashMap object.
HashSet is a set, e.g. {1,2,3,4,5}
HashMap is a key -> value (key to value) map, e.g. {a -> 1, b -> 2, c -> 2, d -> 1}
Notice in my example above that in the HashMap there must not be duplicate keys, but it may have duplicate values.
In the HashSet, there must be no duplicate elements.
They are entirely different constructs. A HashMap
is an implementation of Map
. A Map maps keys to values. The key look up occurs using the hash.
On the other hand, a HashSet
is an implementation of Set
. A Set is designed to match the mathematical model of a set. A HashSet
does use a HashMap
to back its implementation, as you noted. However, it implements an entirely different interface.
When you are looking for what will be the best Collection
for your purposes, this Tutorial is a good starting place. If you truly want to know what's going on, there's a book for that, too.
HashSet is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly.[similarity]
add contains next notes
HashSet O(1) O(1) O(h/n) h is the table
HashMap is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly.[similarity]
get containsKey next Notes
HashMap O(1) O(1) O(h/n) h is the table
Please refer this article to find more information.
It's really a shame that both their names start with Hash. That's the least important part of them. The important parts come after the Hash - the Set and Map, as others have pointed out. What they are, respectively, are a Set - an unordered collection - and a Map - a collection with keyed access. They happen to be implemented with hashes - that's where the names come from - but their essence is hidden behind that part of their names.
Don't be confused by their names; they are deeply different things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With