LordTitiKaka
LordTitiKaka

Reputation: 2156

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?

Upvotes: 1

Views: 1762

Answers (1)

Andy Brown
Andy Brown

Reputation: 19171

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> 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).

Upvotes: 5

Related Questions