Using 'or' in Java Generics declaration
- by Shervin
I have a method that returns an instance of
Map<String, List<Foo>> x();
and another method that returns an instance of
Map<String, Collection<Foo>> y();
Now if I want to dynamically add one of this Maps in my field, how can I write the generics for it to work?
ie:
public class Bar {
private Map<String, ? extends Collection<Foo>> myMap;
public void initializer() {
if(notImportant) myMap = x(); //OK
else myMap = y(); // !OK (Need cast to (Map<String, ? extends Collection<Foo>>)
}
Now is it ok that I cast to the signature even though the y() is declared as being Collection?
}
}
If it is not ok to cast, can I somehow write this (Collection OR List)
I mean, List is a Collection, so it should somehow be possible.
private Map<String, Collection<Foo> | List<Foo>>> myMap;