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/