简体   繁体   English

什么时候将接口用作键类型对HashMaps有意义?

[英]When does using an interface as key-type make sense for HashMaps?

It seems to me that any scenario where I instantiate a HashMap using an interface for a key-type would work contrary to the idea of the map. 在我看来,任何使用键类型的接口实例化HashMap方案都将与映射的概念相反。 Take the following example: 请看以下示例:

HashMap<MyInterface, Integer> map = new HashMap<MyInterface, Integer>();

If I put 2 objects of different MyInterface implementations into the map then they will both operate on their own hashCode() implementations and the entire underlying logic of the HashMap no longer makes sense. 如果我将2个不同MyInterface实现的对象放入映射中,则它们将都在各自的hashCode()实现上运行,并且HashMap的整个基础逻辑不再有意义。 So my question is, is there ever a proper time for using interfaces as keys in HashMaps ? 所以我的问题是,是否有适当的时间在HashMaps使用接口作为键?

they will both operate on their own hashCode() implementations and the entire underlying logic of the HashMap no longer makes sense 它们都将在自己的hashCode()实现上运行,并且HashMap的整个基础逻辑不再有意义

I guess by that you meant hash collision. 我猜您是说哈希冲突。 Hash collision does not corrupt the hash map. 哈希冲突不会破坏哈希映射。 In java, you need to properly implement "equals" together with "hashCode" for the hash map to resolve the key. 在Java中,您需要为哈希映射正确实现“等于”和“ hashCode”,以解析键。

How about: 怎么样:

Map<Connection,AtomicInteger> outstandingQueries = new HashMap<>();

A java.sql.Connection is an interface and this Map makes sense. java.sql.Connection是一个接口,此Map有意义。 Implementation of equals and hashCode can still distinguish objects of different types. equalshashCode实现仍然可以区分不同类型的对象。

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

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