2014-10-16 72 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

相關問題