type参数是X隐藏类型X.

时间:2014-10-16 23:53:57

标签: java types extending

我正在尝试实现此代码。 Rent是Transaction的子类。

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保存的所有对象都是Object类型,并且无法转换为Rent Objects。

1 个答案:

答案 0 :(得分:2)

你很可能意味着

public class TransactionList extends LinkedList<Transaction> { 

你有什么

public class TransactionList<Transaction> extends LinkedList { 

声明一个名为Transaction的新类型变量。所以它等同于

public class TransactionList<T> extends LinkedList { 

并且父类声明是raw。 Read this to understand when and when not to use raw types。在这种情况下,您命名为Transaction的类型参数隐藏了一个名为Transaction的具体类型。

你不能这样做

for(Transaction t : this)

因为thisIterable继承(extends LinkedList),但由于它是原始类型,因此类型会被删除为ObjectObject与类型参数Transaction的分配不兼容。

相关问题