Java Collections – Difference Between HashSet and HashMap

collectionshashmaphashsetjava

Apart from the fact that HashSet does not allow duplicate values, what is the difference between HashMap and HashSet in their implementation?

It's a little bit vague because both use hash tables to store values.

Best Answer

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.

Related Question