How do HashSets in Java work?

madCode picture madCode · Feb 2, 2012 · Viewed 38.7k times · Source

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?

Answer

Bozho picture Bozho · Feb 2, 2012

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.