LinkedList.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
当我编译 LinkedList
类时,我收到此消息。我假设这与我错误地使用泛型有关,但我不太确定我做错了什么。
这是 Node 类和 Linked List 类的代码。
Node.java
public class Node<T> {
private T data;
private Node<T> next;
public Node() {
this.data = null;
this.next = null;
}
public Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
public void setData(T data) {
this.data = data;
}
public void setNext(Node<T> next) {
this.next = next;
}
public T getData() {
return this.data;
}
public Node getNext() {
return this.next;
}
}
LinkedList.java
public class LinkedList<T> {
private Node<T> head;
public LinkedList() {
this.head = null;
}
public LinkedList(Node<T> head) {
this.head = head;
}
public void add(T data) {
if(this.isEmpty())
this.head = new Node<>(data, null);
else {
Node<T> current = this.head;
while(current.getNext() != null)
current = current.getNext();
current.setNext(new Node<>(data, null));
}
}
public T remove() {
Node<T> current = this.head;
Node<T> follow = null;
while(current.getNext() != null) {
follow = current;
current = current.getNext();
}
if(follow == null)
this.head = null;
else
follow.setNext(null);
return current.getData();
}
public int size() {
Node current = this.head;
int count = 0;
while(current != null) {
count++;
current = current.getNext();
}
return count;
}
public boolean contains(T data) {
boolean result = false;
Node current = this.head;
while(current != null) {
if(current.getData() == data)
result = true;
current = current.getNext();
}
return result;
}
public boolean isEmpty() {
return (this.head == null);
}
public String toString() {
if(this.isEmpty())
return "[]";
String output = "[";
Node<T> current = this.head;
while(current != null) {
output += current.getData();
if(current.getNext() != null)
output += ", ";
current = current.getNext();
}
output += "]";
return output;
}
}
最佳答案
此代码会导致编译警告:
public Node getNext() { return this.next; }
当您执行以下操作时:
current = current.getNext();
当 current
声明为:
Node<T> current;
getNext
应该是:
public Node<T> getNext() {
return this.next;
}
以及所有出现 Node
的情况应该是Node<T>
.
关于java - LinkedList.java 使用未经检查或不安全的操作。注: Recompile with -Xlint:unchecked for details,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27478437/