【发布时间】:2022-11-27 21:18:27
【问题描述】:
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;
}
与上面的代码一样,我有一个嵌套 Node 类的通用类 Linkedlist。 代码的功能非常明显(我正在尝试创建一个双向链表)。问题是,在 Node 类的 equals 函数中,我将对象 obj 类型转换为 Node,它给出了我目前已抑制的未经检查的强制转换警告。 来自 vs 代码的自动生成的 equals 函数给出了同样的警告。我知道这个警告一定意味着我的代码在运行时可能会以某种方式中断,但我不知道如何中断,而且我对一般的泛型和编程有点陌生。有什么办法可以解决此警告?
【问题讨论】:
-
“我知道这个警告一定意味着我的代码在运行时可能会以某种方式中断”不,它并不总是意味着那个。演员是安全的。
-
那么有没有什么办法可以“安全地”施放它来消除警告,或者我是否已经抑制了警告?我仍在学习 Java,所以这可以解释我对警告的不满。我只想知道在这里抑制警告是否是最佳做法,或者我可以做更多的事情。
标签: java generics typecasting-operator unchecked-cast