我试图实现此代码。租金是交易的一个子类别。类型参数是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