0

i want to cast a hashmap :

my code:

public class Example {

private HashMap<MyItem, Integer> items =new HashMap<MyItem, Integer>();


@Override
public Map<Item, Integer> gItems() {
    return this.items;
}

}

MyItem is a class who inherit from Item class.

this code give me a compilation error.

For manay reason i can't use the solution to change the type of the return method.

So how can i cast my HashMap<MyItem, Integer> TO a Map<Item, Integer>

The error i'm getting is: Type mismatch:cannot convert from HashMap<MyItem, Integer> to Map<Item, Integer>

and the compilator ask me to change the type of return method.

Thank you.

user3521250
  • 115
  • 3
  • 14

2 Answers2

3

You won't be able to cast because Map<MyItem, Integer> is not a subtype of Map<Item, Integer>. This is described in details in the generics tutorial (see the section Generics and Subtyping).

What you can do in this case is have your function return a Map<? extends Item, Integer>

testinfected
  • 306
  • 1
  • 4
  • thank you , the problem i'm deeling is that when i do a put operation to the collection , it is added even if it is already in the hashmap.for that i'm trying to use a MyItem as a key in the hashmap. – user3521250 Mar 28 '15 at 00:43
  • I'm not sure I understand your comment. What other problem are you having? You can keep the declaration of the map the same, just change the return type of the function – testinfected Mar 28 '15 at 00:51
  • anyway thank you , i think in my case it's not possible – user3521250 Mar 28 '15 at 00:54
1

edit: See testinfected's answer, it's right/makes more sense.

There's probably a problem higher in your stack if code that's calling yours can't handle a type implementing a desired interface, but you can cast like so:

return (Map)this.items;
  • This does not fix the problem. He doesn't need to cast an inheriting class. The issue is that the return type is of Map and the instance type is of HashMap. Note that one uses "Item" as a key and one uses "MyItem" as a key. – michaelgulak Mar 28 '15 at 00:38