简体   繁体   中英

HashMap with key as generic interface

I have an interface dest and some classes implementing this interface:

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

I then have a HashMap<dest,double> destHash . What I want is to instantiate destHash like so:

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:

HashMap<? extends dest, Double> destHash

This says "A HashMap where K is an unknown type that has the upper bound dest ".

The reason is that Foo<Y> is not a subtype of Foo<X> even when Y is a subtype of X . However 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 . For more details see The Java Tutorials > Upper Bounded Wildcards

Note that you need to use the wrapper type Double instead of the primitive as the second type argument.

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. This suggests your design may be incorrect (see Guidelines for Wildcard Use ) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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