作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
我是一名优秀的程序员,十分优秀!