Java: the interface in the collection is not recognized as a parameter

Simple design and simple code, but not compiled:

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 () will not compile. English is bad, but the code should explain. Can someone please find out what is wrong and how to get the design for the suggestion that a list of interface classes could be used in this method?

Again, the English are poor, so they may not express themselves well. Let me know your questions. Thanks!

Error message: SomeMethod (List) method of type ClassCanBeInserted is not applicable for arguments (List)

+7
source share
2 answers

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

+13
source

At first it seems intuitive.

I guess the reason is that the whole point of generics is to enter and keep a list based on static type security.

If you can put any "Insertable" in the list, you can get a mixture of different types of classes, conodata there.

This means that your data is becoming insecure and at risk of ClassCastExceptions.

+1
source

All Articles