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


在上面的代码中,在Boxcar类中执行方法addContents似乎可以正常工作。但是,如果从Person类中以完全相同的方式调用它,则其行为将有所不同。

这是什么原因造成的,我该如何解决?

最佳答案

Java编译器不允许访问未绑定参数化类型(本例中为Boxcar<?>)的引用的方法,因为该类型是未知的。

您应该改为定义通配符的范围,并按如下方式使用它:

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

08-06 04:28