我試圖實現此代碼。租金是交易的一個子類別。類型參數是X隱藏類型X
import java.util.LinkedList;
public class TransactionList<Transaction> extends LinkedList { //TransactionList: warning: The type parameter Transaction is hiding the type Transaction
public TransactionList<Rent> getRentTransactions(){
TransactionList<Rent> rentList = new TransactionList<Rent>();
for(Transaction t : this){ //this: error: Type mismatch: cannot convert from element type Object to Transaction
if(t instanceof Rent){
t = (Rent) t; //this: warning: Type mismatch: cannot convert from Rent to Transaction
rentList.add((Rent) t);// whole statement: warning: Type safety: The method add(Object) belongs to the raw type LinkedList. References to generic type LinkedList<E> should be parameterized
}
}
return rentList;
}
我真的失去了這一點,我絕對相信這個代碼是類型安全的任何給定的TransactionList總是包含交易或交易的一個子類。
但是,如果我改變了語句
for(Object t : this)
它會編譯。但是,返回的TransactionList所擁有的所有對象都是Object類型的,並且無法將其轉換爲租用對象。
是的,對不起,感到抱歉 – nitowa 2014-10-17 00:03:43