0

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?

Andy Brown
  • 18,200
  • 3
  • 46
  • 59
LordTitiKaka
  • 1,856
  • 1
  • 24
  • 41

1 Answers1

4

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

Andy Brown
  • 18,200
  • 3
  • 46
  • 59
  • I'm rewriting some "historic" code , and this will greatly reduce the amount of work I need to do , can you explain please why I wont be able to use the hashmap ? – LordTitiKaka Aug 02 '15 at 12:56
  • also you are correct about the value type , I wrote it just for the example – LordTitiKaka Aug 02 '15 at 12:58
  • @LordTitiKaka. You need to read the links I put in the question. The key is to understand inheritance for generic types, then to understand lower/upper bounded wildcards and the get/set (or [PECS](http://stackoverflow.com/a/4343547/1945631)) principle. That will help you achieve what you need to do. – Andy Brown Aug 02 '15 at 12:59
  • your guides helped figures stuff that I didn't know before ! thanks :) – LordTitiKaka Aug 02 '15 at 15:23