【问题标题】:Why can't I call a method with a list of enum which implement an interface?为什么我不能使用实现接口的枚举列表调用方法?
【发布时间】:2011-08-02 09:36:28
【问题描述】:

我正在尝试调用一个方法,该方法采用一个接口列表和一个枚举列表(实现接口)。这会产生以下编译错误:

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

这是界面:

public interface Interface {
}

这是实现接口的枚举:

public enum Enum implements Interface {
}

这是调用类:

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.
    }
}

为什么会出现编译错误?在我看来,它应该可以工作,因为 Enum 实现了该接口。

【问题讨论】:

  • Generics in Java的可能重复
  • 是的,这是重复的。我之前找的时候找不到那个。

标签: java generics enums


【解决方案1】:
public static void method(List<? extends Interface> list){
}

【讨论】:

    【解决方案2】:

    这是因为 even 是 Car 扩展 VehicleList&lt;Car&gt; 扩展 List&lt;Vehicle&gt;。如果是这样,您可以执行以下操作:

    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.
    

    【讨论】:

    • 请注意,您可以对数组执行相同的操作(导致 ArrayStoreException),并且无法修复以保持兼容性。
    【解决方案3】:

    因为List&lt;Enum&gt; 不是List&lt;Interface&gt;

    您应该将变量更改为List&lt;Interface&gt;,或者将方法签名更改为List&lt;? extends Interface&gt;

    【讨论】:

      【解决方案4】:

      虽然 Enum 实现了接口,但 List 不是 List 的子类型。 如果您将方法签名修改为以下将起作用。

      method(List<? extends Interface> list)
      

      有关更多详细信息,请参阅文档 http://download.oracle.com/javase/tutorial/java/generics/wildcards.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-12
        • 2015-03-14
        • 1970-01-01
        • 1970-01-01
        • 2015-02-12
        • 1970-01-01
        • 2011-04-26
        • 2013-05-11
        相关资源
        最近更新 更多