简体   繁体   English

是否可以实现由给定HashSet实现支持的MyHashMap?

[英]Is it possible to implement a MyHashMap backed by a given HashSet implementation?

As we all known, in Sun(Oracle) JDK, HashSet is implemented backed by a HashMap , to reuse the complicated algorithm and data structure. 众所周知,在Sun(Oracle)JDK中, HashSetHashMap支持,以重用复杂的算法和数据结构。 But, is it possible to implement a MyHashMap using java.util.HashSet as its back? 但是,是否可以使用java.util.HashSet作为其背面实现MyHashMap If possible, how? 如果可能,怎么样? If not, why? 如果没有,为什么?

Please note that this question is only a discussion of coding skill, not applicable for production scenarios. 请注意,此问题仅是对编码技巧的讨论,不适用于生产场景。

Trove bases it's Map on it's Set implementation. Trove将它的Map基于它的Set实现。 However, it has one critical method which is missing from Set which is a get() method. 但是,它有一个缺少Set的关键方法,它是一个get()方法。

Without a get(Element) method, HashSet you cannot perform a lookup which is a key function of a Map. 如果没有get(Element)方法,HashSet就无法执行查找,这是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. (原谅双关语)唯一的选择Set是一个包含可以被黑客攻击来执行get()但它不是理想的。

You can have; 你可以有;

  • a Set where the Entry is a key and a value. a Entry是键和值的集合。
  • 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. 你破解equals()方法所以当匹配时,在“put”上更新条目的值部分,并在“get”上复制值部分。

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. Set可以被设计为扩展为Map,但它不是,并且使用HashSet或现有的Set实现来创建Map不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM