gpt4 book ai didi

java - 继承和集合相关的编译错误

转载 作者:行者123 更新时间:2023-12-05 00:56:24 24 4
gpt4 key购买 nike

我想弄清楚为什么这段代码无法编译。

我通过接口(interface) B 扩展了接口(interface) A。实现接口(interface) B 的类 C。

当我调用一个接受单个 A 类型对象的方法时,我可以传入一个 C 类型的对象,这没问题。

当我调用接受类型 A 的 java.util.List 的方法时,我无法传入类型 C 的对象的 java.util.List。Eclipse 生成以下错误:类型 Test1 中的方法 addAList(List) 不适用于参数 (List)

源代码示例如下。

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

public class Test1 {

public void addASingle(A a) {
return;
}

public void addAList(List<A> aList) {
return;
}

// **********************************

public static void main(String[] args) {
Test1 t = new Test1();

C c1 = new C();
List<C> cList = new ArrayList<C>();
cList.add(c1);

t.addASingle(c1); // allowed

t.addAList(cList); // The method addAList(List<Test1.A>)
// in the type Test1 is not applicable for the arguments (List<Test1.C>)
}

// **********************************

public static interface A {
}

public static interface B extends A {
}

public static class C implements B {
}
}

最佳答案

A List<Car>不是 List<Vehicle> .如果是,您可以执行以下操作:

List<Car> cars = new ArrayList<>();
List<Vehicle> vehicles = cars;
vehicles.add(new Bicycle());

你最终会得到一个包含自行车的汽车列表。它会破坏泛型集合的类型安全。

您可能应该使用 List<? extends A>而不是 List<A> . List<? extends A>意思是:一个List<some class which is A or which extends A> .

关于java - 继承和集合相关的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11245272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com