Using 'or' in Java Generics declaration

Posted by Shervin on Stack Overflow See other posts from Stack Overflow or by Shervin
Published on 2010-06-02T15:42:13Z Indexed on 2010/06/02 15:43 UTC
Read the original article Hit count: 269

Filed under:
|
|

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;

© Stack Overflow or respective owner

Related posts about java

Related posts about generics