2014-10-16 54 views
0

我试图实现此代码。租金是交易的一个子类别。类型参数是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类型的,并且无法将其转换为租用对象。

+0

是的,对不起,感到抱歉 – nitowa 2014-10-17 00:03:43

回答

2

你更可能意味着

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) 

因为thisIterable通过继承(extends LinkedList),但因为它是一个原始类型,该类型擦除ObjectObject与类型参数Transaction不兼容。

+0

感谢您的大力解释。我现在觉得有点傻了! :) – nitowa 2014-10-17 00:11:54