如何創建通用清單列表?我有一個Boxcar類,它需要一個通用參數和一個應該創建Boxcars列表的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;
}
}
我希望這更好的時候傳達什麼,我試圖完成
目前還不清楚你試圖達到什麼目標,但上面的代碼將定義不能編譯。 – amit
我認爲你應該定義使用列表的類,而不是列表。 – Bohemian