gpt4 book ai didi

java - 泛型双重标准

转载 作者:行者123 更新时间:2023-12-02 07:24:36 27 4
gpt4 key购买 nike

public class Boxcar<S extends Things> {
public ArrayList<S> contents = new ArrayList<S>(); //an arraylist of things

public static void main(String [] args){
Boxcar test = new Boxcar();
test.addContents(new Person("239-235-2535", "Ronald", 36)); //works 100%
}

public Boxcar(Things type, int maxElements){
this.type = type;
boxcarId = boxcarIdCount;
boxcarIdCount++;
this.maxElements = maxElements;
}

public void addContents(S thing) {
contents.add(thing);
}
...

}//end boxcar class

public class Person implements Things {
int age;
String govtId, name;

public Person(String govtId, String name, int age){
this.govtId = govtId;
this.name = name;
this.age = age;
}//end Consrtructor

public void load(ArrayList<Boxcar<?>> train){
Person dude = new Person("239-235-235", "Ronald", 36);
train.get(i).addContents(dude); // won't compile
}
...
}//end Person class

public interface Things {

public void load(ArrayList<Boxcar<?>> train, String [] params);

}//end interface Things

public class Train {
ArrayList<Boxcar<?>> train = new ArrayList<Boxcar<?>>();

public void load(Things thing, String [] params){
thing.load(train, params);
}
...
}

在上面的代码中,方法 addContents 在 Boxcar 类中执行时似乎工作正常。然而,当从 Person 类以完全相同的方式调用时,它的行为会有所不同。

造成这种情况的原因是什么以及如何解决?

最佳答案

Java 编译器不允许访问未绑定(bind)参数化类型的引用上的方法,Boxcar<?>在您的情况下,因为类型未知。

您应该定义通配符的界限并按如下方式使用它:

public void load(ArrayList<Boxcar<? super Things>> train)
{
Person dude = new Person("239-235-235", "Ronald", 36);
train.get(0).addContents(dude);
}

关于java - 泛型双重标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13716499/

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