简体   繁体   English

使用键作为通用接口的HashMap

[英]HashMap with key as generic interface

I have an interface dest and some classes implementing this interface: 我有一个interface dest和一些实现此接口的类:

class destImpl1 implements dest { ... } 
class destImpl2 implements dest { ... }

I then have a HashMap<dest,double> destHash . 然后,我有一个HashMap<dest,double> destHash What I want is to instantiate destHash like so: 我想要的是像这样实例化destHash

destHash = new HashMap<destImpl1,double>();

and later like this: 然后像这样:

destHash = new HashMap<destImpl2,double>();

but the code doesn't compile. 但是代码无法编译。 What am I missing here? 我在这里想念什么?

Declare destHash as: destHash声明为:

HashMap<? extends dest, Double> destHash

This says "A HashMap where K is an unknown type that has the upper bound dest ". 这表示“ HashMap ,其中K是具有上限dest的未知类型”。

The reason is that Foo<Y> is not a subtype of Foo<X> even when Y is a subtype of X . 其原因是, Foo<Y>不是的子类型Foo<X>即使当Y是的子类型X However Foo<? extends X> 但是Foo<? extends X> Foo<? extends X> represents the set of all possible generic type invocations of Foo<T> where the type parameter is a subtype of X . Foo<? extends X>表示Foo<T>的所有可能的泛型类型调用的集合,其中type参数是X的子类型。 For more details see The Java Tutorials > Upper Bounded Wildcards 有关更多详细信息,请参见Java教程>上限通配符。

Note that you need to use the wrapper type Double instead of the primitive as the second type argument. 请注意,您需要使用包装类型Double而不是原始类型作为第二个类型参数。

Comment: However, if you do this you may not be able to actually use the HashMap as you won't be able to put keys and values into it. 注释: 但是,如果执行此操作,则可能无法实际使用HashMap因为您将无法在其中put键和值。 This suggests your design may be incorrect (see Guidelines for Wildcard Use ) . 这表明您的设计可能不正确(请参阅通配符使用准则

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

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