I think I made some mistake while writing my code. I have a class MyClass that implements Interface, now I've a method that is generic for List of Interface as a parameter. I want to use my method by passing a List. I can't cast from List to List (that I assumed I could). So, what can I do to make my code work? here an example:
List<MyClass> lista = returnMyClassList();
myMethod((List<Interface>) lista); //this doesn't work
//myMethod signature
public void myMethod(List<Interface> struttura);
Thanks for helping.
Use an upper bound of Interface
for the type: <? extends Interface>
.
Here's come compilable code that uses classes from the JDK to illustrate:
public static void myMethod(List<? extends Comparable> struttura) {}
public static void main(String[] args) {
List<Integer> lista = null;
myMethod(lista); // compiles OK
}
You should use public void myMethod(List<? extends Interface> struttura);
. This way you will be able to pass any type that IS-A
Interface
. You would like to read about Polymorpshism and generics
List<MyClass>
is not a sub type of List<Interface>
you are getting error.
Accorind to java docs
Given two concrete types A and B (for example, Number and Integer), MyClass has no relationship to MyClass, regardless of whether or not A and B are related. The common parent of MyClass and MyClass is Object
So Change your method signature to
public void myMethod(List<? extends Interface> struttura){
}
and call the method
List<MyClass> lista = returnMyClassList();
myMethod((lista);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With