0

I am trying to call a method which takes a list of Interface with a list of Enum (which implements Interface). This gives the following compile error:

The method method(List<Interface>) in the type Class is not applicable for the arguments (List<Enum>)

This is the interface:

public interface Interface {
}

This is the enum that implements the interface:

public enum Enum implements Interface {
}

This is the calling class:

import java.util.ArrayList;
import java.util.List;

public class Class {
    public static void method(List<Interface> list){
    }

    public static void main(String[] args) {
        List <Enum> enumList = new ArrayList<Enum>();
        method(enumList); //This line gives the compile error.
    }
}

Why is there a compile error? To me it seems that it should work because the Enum implements that interface.

2
  • 2
    possible duplicate of Generics in Java Commented Aug 2, 2011 at 9:40
  • Yes, that is a duplicate. I couldn't find that one when I was looking earlier. Commented Aug 2, 2011 at 9:52

4 Answers 4

5
public static void method(List<? extends Interface> list){
}
Sign up to request clarification or add additional context in comments.

Comments

1

This is because even is Car extends Vehicle, List<Car> does not extend List<Vehicle>. If it did, you could do the following:

List<Car> listOfCars = new ArrayList<Car>();
List<Vehicle> listOfVehicles = listOfCars;
listOfVehicles.add(new Bicycle());
// and now the list of cars contains a bicycle: not pretty.

1 Comment

Note that you can do the same thing with arrays (results in an ArrayStoreException), and that cannot be fixed to preserve compatibility.
1

Because List<Enum> is-not-a List<Interface>.

You should either change the variable to List<Interface>, or change the method signature to take List<? extends Interface>

Comments

1

Though the Enum implements the Interface, List< Enum > is not subtype of List < Interface >. If you modify the method signature to following will work.

method(List<? extends Interface> list)

For further details go through the documentation http://download.oracle.com/javase/tutorial/java/generics/wildcards.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.