gpt4 book ai didi

java - LinkedList.java 使用未经检查或不安全的操作。注意 : Recompile with -Xlint:unchecked for details

转载 作者:行者123 更新时间:2023-11-30 08:58:51 24 4
gpt4 key购买 nike

LinkedList.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.

我在编译 LinkedList 类时收到此消息。我假设这与我错误地使用泛型有关,但我不确定我做错了什么。

下面是 Node 类和 Linked List 类的代码。


节点.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;
}

}

链表.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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com