Domanda

As we all known, in Sun(Oracle) JDK, HashSet is implemented backed by a HashMap, to reuse the complicated algorithm and data structure. But, is it possible to implement a MyHashMap using java.util.HashSet as its back? If possible, how? If not, why?

Please note that this question is only a discussion of coding skill, not applicable for production scenarios.

È stato utile?

Soluzione

Trove bases it's Map on it's Set implementation. However, it has one critical method which is missing from Set which is a get() method.

Without a get(Element) method, HashSet you cannot perform a lookup which is a key function of a Map. (pardon the pun) The only option Set has is a contains which could be hacked to perform a get() but it would not be ideal.

You can have;

  • a Set where the Entry is a key and a value.
  • you define entries as being equal when the keys are the same.
  • you hack the equals() method so when there is a match, that on a "put" the value portion of an entry is updated, and on a "get" the value portion is copied.

Set could have been designed to be extended as Map, but it wasn't and it wouldn't be a good idea to use HashSet or the existing Set implementations to create a Map.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top