Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics - passing a collection of subtype to a method requiring a collection of base type

Tags:

java

generics

How to do this in Java - passing a collection of subtype to a method requiring a collection of base type?

The example below gives:

The method foo(Map<String,List>) is not applicable for the arguments (Map<String,MyList>)

I can implement by creating a class hierarchy for the typed collections - but is it possible otherwise?

public void testStackOverflow() {

    class MyList extends AbstractList {
        public Object get(int index) {
            return null;
        }
        public int size() {
            return 0;
        }           
    };

    Map <String, List>   baseColl = null;
    Map <String, MyList> subColl  = null;

    foo (subColl);              
}

private void foo (Map <String, List> in) {      
}

EDIT: Turns out from the answers that this requires "bounded wildcard" so adding this text for searchability

like image 697
horace Avatar asked Nov 18 '08 09:11

horace


2 Answers

Change foo to:

private void foo(Map <String, ? extends List> in) {
}

That will restrict what you can do within foo, but that's reasonable. You know that any value you fetch from the map will be a list, but you don't know what kind of value is valid to put into the map.

like image 89
Jon Skeet Avatar answered Nov 15 '22 04:11

Jon Skeet


as jon s says:

private void foo (Map <String, ? extends List> in { ... }

will fix the errors. you will still have warnings though. take a look the get-put principle at: http://www.ibm.com/developerworks/java/library/j-jtp07018.html

like image 41
Ray Tayek Avatar answered Nov 15 '22 04:11

Ray Tayek