Possible Duplicate:
How does Java hashmap work?
Can someone explain to me how HashSets in java work and why they are faster than using ArrayLists?
If the hashcode of two objects are equal then hashset uses equal() to see if the hashcode matched objects are really equal. And if they are equal the hashset knows that the new object is duplicate of something exist in the HashSet. And the add does not happen. The add() of hashcode returns false.
Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys.
HashSet doesn't allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten. HashSet allows null values however if you insert more than one nulls it would still return only one null value. HashSet is non-synchronized.
HashSet cannot contain duplicate values. HashSet allows null value. HashSet is an unordered collection. It does not maintain the order in which the elements are inserted.
A HashSet
is actually a HashMap
where the value is always the same.
The way a HashMap
works is described in many places (it is referred to as "hashtable" as well). In short: it generates hashes of keys (objects) and positions them into a table. Then each time you look for a key, its hash is computed and the bucket in the table is referenced directly. This means you have just one operation (best case) to access the map.
The HashSet
simply contains the keys, so .contains(..)
is O(1)
. That and remove(..)
are the only operations a HashSet
is faster than an ArrayList
(which is O(n)). Iteration is the same, addition is the same.
First, HashSet
, unlike ArrayList
is a Set: It cannot contain duplicates while ArrayList
can - so they are built for different purposes. It also does not guarantee ordering - again, unlike a list.
Second - a HashSet
is built on the hash table data structure, that allows O(1)
seek time for an element.
Note that many times, a HashSet
is slower then an ArrayList
- if you want to iterate on elements for example - usually doing it in an ArrayList
will be faster then in a HashSet
[because of bad cache performance of hash, among other reasons]
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