Chr*_*ris 0 java generic-list nullpointerexception
我一直在搜索stackoverflow上的1000个NullPointerException帖子,并且在我的生活中不能说明为什么会发生这种情况; 除了明显的(它是空的).有人可以帮助我理解我不理解Generic Singly LinkedList导致我得到这个运行时错误的内容.
这是我的代码:
import java.io.*;
import java.util.*;
public class GList<T> {
private GNode<T> head;
private GNode<T> cursor;
private static class GNode<E>{
private E data; //NULLPOINTEREXCEPTION
private GNode<E> next;
public GNode(E data, GNode<E> next) {
this.data = data;
this.next = next;
}
}
public static class InnerList<E> {
private String name;
private GList<Integer> inner = new GList<Integer>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public GList<Integer> getInner() {
return inner;
}
public void setInner(GList<Integer> inner) {
this.inner = inner;
}
}
public boolean hasNext(T cursor) {
/*
* returns whether or not the node pointed to by 'cursor' is
* followed by another node. If 'head' IS null, returns False
*/
if (cursor != null)
{
return true;
}
else
{
return false;
}
}
public void insertFirst(T t) {
/*
* puts a new node containing t as a new first element of the list
* and makes cursor point to this node
*/
if (hasNext(t) == false){
head = new GNode<T>(t, head);
head.next.data = t;
cursor.next = head;
}
else{
System.out.println("List is not null.");
}
}
public static void main(String[] args){
GList<InnerList> list = new GList<InnerList>();
String ln = "hello";
list.cursor.next.data.setName(ln); //NULLPOINTEREXCEPTION
/*Exception in thread "main" java.lang.NullPointerException
*at GList$GNode.access$0(GList.java:10)
*at GList.main(GList.java:67)
*/
}
}
Run Code Online (Sandbox Code Playgroud)
这是家庭作业,所以解释将是最有帮助的,因为我相信我将在未来几个月内处理LinkedList.
由于您使用的是默认构造函数,因此您尚未给出实现
GList<InnerList> list = new GList<InnerList>();
Run Code Online (Sandbox Code Playgroud)
它的所有字段都没有被初始化等等
list.cursor == null
Run Code Online (Sandbox Code Playgroud)
Java在此处停止执行,但您的其他字段也为空.花点时间重新访问代码并初始化所有相关字段.
事实上,您不应该尝试访问列表中的任何内容,因为您尚未向其中添加任何项目.其head和cursor为空.