Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast from List<MyClass> to List<Interface>

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.

like image 251
Pievis Avatar asked Sep 17 '13 13:09

Pievis


3 Answers

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
}
like image 158
Bohemian Avatar answered Oct 11 '22 22:10

Bohemian


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

like image 39
Prasad Kharkar Avatar answered Oct 11 '22 22:10

Prasad Kharkar


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);
like image 27
Prabhaker A Avatar answered Oct 11 '22 22:10

Prabhaker A