我正在尝试实现此代码。租金是交易的子类。
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 将始终包含 Transaction 或 Transaction 的子类。
但是如果我将 for 语句更改为
for(Object t : this)
它将编译。然而,返回的 TransactionList 持有的所有对象都将是对象类型,并且无法转换为租赁对象。
最佳答案
你很可能是这个意思
public class TransactionList extends LinkedList<Transaction> {
你拥有什么
public class TransactionList<Transaction> extends LinkedList {
声明一个名为Transaction
的新类型变量。所以它相当于
public class TransactionList<T> extends LinkedList {
并且父类声明是原始的。 Read this to understand when and when not to use raw types 。在本例中,您命名为 Transaction
的类型参数隐藏了一个也名为 Transaction
的具体类型。
你不能这样做
for(Transaction t : this)
因为 this
是通过继承(extends LinkedList
)实现的 Iterable
,但由于它是原始类型,因此类型会被删除为 对象
。 Object
与类型参数 Transaction
的赋值不兼容。
关于java - 类型参数是 X 隐藏类型 X,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26415785/