1

I'm trying to pass a variable of the type:

HashMap<Foo, HashSet<Bar>>

to a method, which expects:

Map<Foo, Set<Bar>>

I think it should work, but I'm getting the following compile error:

java: method setMenu in class com.xx.client.layout.Layout cannot be applied to given types;

  required: java.util.Map<com.xx.shared.model.UserType,java.util.Set<com.xx.shared.dto.model.MenuItemDTO>>

  found: java.util.HashMap<com.xx.shared.model.UserType,java.util.HashSet<com.xx.shared.dto.model.MenuItemDTO>>

  reason: actual argument java.util.HashMap<com.xx.shared.model.UserType,java.util.HashSet<com.xx.shared.dto.model.MenuItemDTO>> 

cannot be converted to 

java.util.Map<com.xx.shared.model.UserType,java.util.Set<com.xx.shared.dto.model.MenuItemDTO>> 

by method invocation conversion
Ali
  • 261,656
  • 265
  • 575
  • 769

1 Answers1

2

To attempt to convince you, given a

HashMap<Foo, HashSet<Bar>> myMap;

you would expect to do

HashSet<Bar> aHashSet = myMap.get(aFoo);

But if you had

public void someMethod(Map<Foo, Set<Bar>> aMapParameter) {...}

and expected

someMethod(myMap); 

to work, then someMethod could simply do

public void someMethod(Map<Foo, Set<Bar>> aMapParameter) {
    aMapParameter.put(aFoo, new TreeSet<>());
}

Your original

HashSet<Bar> aHashSet = myMap.get(aFoo);

would fail with a ClassCastException.

Compile time type safety has to guarantee that this doesn't happen. Therefore the compiler doesn't allow that method call.

Related:

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724