Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: interface in collection not recognized as parameter

Simple design and simple code but don't compile:

public interface Insertable {
    public String getInsertStmt(String table);
}

public class ClassCanBeInserted implements Insertable { 
    public String getInsertStmt(String table) {}
}

public class SomeClass { 
    public static void main() { 
        List<ClassCanBeInserted> list = new ArrayList<ClassCanBeInserted>();
        SomeMethod(list);
    }
    private static void SomeMethod(List<Insertable> list) {}
}

And the call to SomeMethod() won't compile. English poor but the code should explain. Can someone please figure out what's wrong and how to get a design for the propose that a list of interface-implemented classes can be used in such method?

Again, English poor, so may not expressed well. Let me know your questions. Thanks!

Error message given: The method SomeMethod(List) in the type ClassCanBeInserted is not applicable for the arguments (List)

like image 312
X.M. Avatar asked Dec 16 '10 08:12

X.M.


1 Answers

List<Insertable> is not a superclass of List<ClassCanBeInserted>, even though Insertable is a superclass of ClassCanBeInserted. To do what you want, you should change the SomeMethod signature to SomeMethod(List<? extends Insertable> list).

like image 113
Jordi Avatar answered Sep 18 '22 19:09

Jordi