java - 类型参数是 X 隐藏类型 X

标签 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> 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/

相关文章:

linux - 什么类型的数据默认返回/dev/random?

java - 摆脱 Map 中的泛型

java - 扩展 Activiti 流程引擎功能的首选方式是什么?

带有缺少括号的函数调用的 JavaScript 语言扩展 - 它们可能吗?

java - Neo4j 的 POM 文件中应该包含什么?

Java:public static final double 不能设置为小数?

java - 如何从命令行执行 java .class

java - 将数据从 packetlistener 服务发送到 UI

c# - 使用 var 关键字自动交换显式类型

Haskell 函数接受一个类型和一个值并检查值是否具有该类型