gpt4 book ai didi

java - 需要帮助诊断 NullPointerException

转载 作者:行者123 更新时间:2023-11-29 05:26:41 25 4
gpt4 key购买 nike

<分区>

我是泛型的新手,我正在尝试制作一个链表。

这是 Node_ 类的代码。

public class Node_<T> {

private int index;
private T data;
private Node_<T> next;
public Node_() {
}

public Node_(T data, int index) {
this.data = data;
this.index = index;
next = null;
}

public void set(T data, int index) {
this.data = data;
this.index = index;
this.next= null;
}

public void display() {
System.out.println(this.data.toString());
}

public void setindex(int index) {
this.index = index;
}

public void setData(T data) {
this.data = data;
}

public Node_<T> getNext() {
return next;
}

public boolean hasNext() {
if (next != null) return true;
else return false;
}

public int getIndex() {
return this.index;
}
}

和链表类。

public class LinkList<T> {    
private int total = 0;
private Node_<T> start;
private Node_<T> end;
private Node_<T> ptr;

public LinkList() {
}

public LinkList(T data) {
start = new Node_<T>(data, 0);
end = start;
ptr = start;
total++;
}

public void add(T data) {
if (start == null) {
start = new Node_<T>(data, 0);
end = start;
ptr = start;
total++;
} else {
end.set((T) data,(int) total);
total++;
end = end.getNext();
}
}


public void displayAt(int index) {
if (start != null) {
ptr = start;
do {
if (ptr.getIndex() == index)
ptr.display();
} while (ptr.hasNext());
}

else
System.out.println("No Element found");
}

public void displayAll() {
if (start != null) {
ptr = start;
do {
ptr.display();
} while (ptr.hasNext());
}

else
System.out.println("No Element Present");
}
}

主类中的以下代码

public class Main {
public static void main(String[] args) {
LinkList<Integer> list = new LinkList<Integer>(25);
list.displayAll();
for (int i = 0; i < 11; i++) {
list.add((Integer) i);
}
list.displayAll();
}

}

我收到以下错误,我无法找出问题所在。

25
Exception in thread "main" java.lang.NullPointerException
at LinkList.add(LinkList.java:26)
at Main.main(Main.java:8)

任何我哪里出错的建议。

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