Java 类型参数为X,隐藏类型X
我正在尝试实现这个代码。租金是交易的一个子类Java 类型参数为X,隐藏类型X,java,types,extending,Java,Types,Extending,我正在尝试实现这个代码。租金是交易的一个子类 import java.util.LinkedList; public class TransactionList<Transaction> extends LinkedList { //TransactionList: warning: The type parameter Transaction is hiding the type Transaction public TransactionList<Rent> get
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所持有的所有对象都将是Object类型,并且无法强制转换为Rent对象。您的意思可能是
public class TransactionList extends LinkedList<Transaction> {
父类声明是原始的。在本例中,您命名为Transaction
的类型参数隐藏了一个名为Transaction
的具体类型
你不能这么做
for(Transaction t : this)
因为
此
通过继承(扩展LinkedList
)是一个可编辑的
),但由于它是一个原始类型,因此该类型被擦除为对象
。对象
与类型参数事务
的赋值不兼容是的,非常抱歉造成混淆感谢您的澄清。我现在觉得有点傻!:)
public class TransactionList<Transaction> extends LinkedList {
public class TransactionList<T> extends LinkedList {
for(Transaction t : this)