Rohit
Rohit

Reputation: 196

Can hash set internally use some other collection instead of hash map

Why is it like Hash set internally only used Hash map ? Is it something related with performance?

Upvotes: 2

Views: 123

Answers (3)

QuentinC
QuentinC

Reputation: 14742

Since HashMap and HashSet are basicly using the same algorithm, it is simpler not to implement it twice, and therefore it isn't surprising that a few, if not all, JVM implementation do it. It is also doable with LinkedHashMap/Set, TreeMap/Set and others.

More generally, it is possible to create any Set implementation from any Map implementation by choosing the value as being the same as the key, or be a constant. The loss in memory storage is negligible.

By the way, the JDK provides a Collections.newSetFromMap method which does exactly this: it converts a Map<E,Boolean> into a Set<E> by mapping all keys to Boolean.TRUE. When there is no corresponding Set implementation to a Map one, this utility method is very useful, for example for ConcurrentHashMap.

The opposite, creating a Map implementation from a Set one, is also doable, though it's slightly more difficult.

Upvotes: 0

Uri
Uri

Reputation: 89749

A HashSet can be thought of as a special case of a HashMap in which you don't actually care about the type of values, only whether a value is associated with a particular key.

So, it made sense to just implement one on top of the other. A HashMap is a good choice if your key type has a good hash function.

Similarly, TreeSet is implemented using TreeMap, which can be effective if your keys are ordered/comparable.

You can implement the Set interface in many other ways, but these are the typical ones.

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198093

Nah, it's just convenient, and not actually any less efficient on most VMs. So Java -- at least in some implementations -- doesn't bother doing anything fancier.

Upvotes: 0

Related Questions