java - 类型转换为嵌套在泛型类中的类

标签 java generics typecasting-operator unchecked-cast

package LinkedList;

public class Linkedlist<T> {
    private int size;
    Node head;
    Node tail;

    public Linkedlist() {// default constructor
        size = 0;
        head = null;
        tail = null;
    }

    public class Node {// Node class
        T data;// current node data
        Node next;// reference to next node
        Node prev;// reference to previous node

        public Node(T data) {// def constructor
            this.data = data;
            next = null;
            prev = null;
        }

        @Override // to check equality of two nodes
        public boolean equals(Object obj) {
            if (this == obj)// checks if both have same reference
                return true;
            if (obj == null ||this==null || this.getClass() != obj.getClass())
                return false;
            @SuppressWarnings("unchecked")//casting obj to node gives a unchecked cast warning.
            Node n=((Node)obj);
            if(!(this.data==n.data))
                return false;
            return true; 
        }

如上面的代码所示,我有一个泛型类 Linkedlist,它嵌套一个 Node 类。代码的功能非常明显,我正在尝试创建一个双向链表。

问题是,在 Node 类的 equals 函数中,我将对象 obj 类型转换为 Node,这会给出一个未经检查的转换警告,目前我已经抑制了该警告。 Visual Studio Code 自动生成的 equals 函数给出了同样的警告。我知道这个警告一定意味着我的代码在运行时可能会以某种方式中断,但我不知道如何中断,而且我对泛型和编程很陌生。有什么办法可以解决这个警告吗?

最佳答案

您可以使用它来避免强制转换警告

if (!(obj instanceof LinkedList<?>.Node)) return false;
LinkedList<?>.Node node = (LinkedList<?>.Node) obj;

关于java - 类型转换为嵌套在泛型类中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74589856/

相关文章:

java - 打印前 6 个梅森素数代码的代码?

java - spring 5 中 Autowiring 的通用

C 指针转换

c - 为什么 -Wcast-align 不警告在 x86 上从 char* 到 int* 的转换?

java - 多线程服务器: SwingWorker Vs Thread?

java - Hibernate:如何解决 java.lang.IncompatibleClassChangeError:

java - 无法从另一个类调用主类的静态方法

java - 从 Java 中的枚举属性获取泛型类的实例

c - 为什么函数无法访问泛型参数

c++ - 如何避免强制转换运算符() 和访问运算符[] 冲突?