1

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?

5
  • 3
    Java Generics does not support primitive types. You need to use the boxed Double class. Commented Aug 2, 2015 at 12:24
  • 1
    What is the compile error? Commented Aug 2, 2015 at 12:37
  • @Gaber-ber my error is: Type mismatch: cannot convert from LinkedHashMap<Dest,Double> to HashMap<destImpl1,Double> Commented Aug 2, 2015 at 12:53
  • I'm more worried about what you're trying to achieve here. While you can get these lines to compile using an upper-bounded wildcard you won't actually be able to use the destHash to store anything if you do. Commented Aug 2, 2015 at 12:54
  • @AndyBrown can you please explain why is that (the storing problem) Commented Aug 2, 2015 at 12:57

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

4 Comments

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 ?
also you are correct about the value type , I wrote it just for the example
@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) principle. That will help you achieve what you need to do.
your guides helped figures stuff that I didn't know before ! thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.