如何创建通用列表列表?我有一个带有通用参数的 Boxcar 类和一个应该创建 Boxcar 列表的 Train 类。我们应该在一个单独的主类中指定 Boxcar 中的类型,因此在此之前,boxcar 必须保持通用。以下是我编写的代码。它可以编译,但在调用加载方法时在单独的驱动程序类中出现错误The method load(capture#1-of ?) in the type Boxcar<capture#1-of ?> is not applicable for the arguments (Person)
package proj5;
import java.util.ArrayList;
import java.util.List;
public class Train {
private List<Boxcar<?>> train;
private int maxSpeed;
private int minSpeed;
private String position;
private int numBoxcars;
private int maxNumBoxcars;
private int speed;
private String destination;
private boolean stopped = true;
public Train(int maxSpeed, int minSpeed, int maxNumBoxcars, String position){
train = new ArrayList<Boxcar<?>>();
this.maxSpeed = maxSpeed;
this.minSpeed = minSpeed;
this.maxNumBoxcars = maxNumBoxcars;
this.position = position;
}
public int getMaxNumBoxcars(){
return maxNumBoxcars;
}
public int getSpeed(){
return speed;
}
public String getPosition(){
return position;
}
public int getMaxSpeed(){
return maxSpeed;
}
public int getNumBoxcars(){
return numBoxcars;
}
public List<Boxcar<?>> getTrain(){
return train;
}
public void depart(String destination){
this.destination = destination;
speed = minSpeed;
stopped = false;
}
public void arrive(){
stopped = true;
position = destination;
}
public void addCar(Boxcar<?> boxcar, int i){
if(stopped){
boxcar.setMaxItems(i);
train.add(boxcar);
}
}
public void removeCar(int i){
if(stopped){
train.remove(i);
}
}
}
package proj5;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
public class Boxcar<T extends Comparable<T>> {
private List<T> boxcar;
private int maxItems;
public Boxcar(){
boxcar = new ArrayList<T>();
}
public void load(T thing){
if(!boxcar.contains(thing) && boxcar.size() < maxItems){
boxcar.add(thing);
Collections.sort(boxcar);
}else{
}
}
public int getMaxItems(){
return maxItems;
}
public void setMaxItems(int i){
maxItems = i;
}
public void unload(T thing){
boxcar.remove(thing);
}
public List<T> getBoxcar(){
return boxcar;
}
}
我希望这能更好地传达我想要完成的事情