I’ve been scouring the 1000’s of NullPointerException posts on stackoverflow and cannot for the life of me figure why this is happening; aside from the obvious (that it is null). Can someone help me understand what it is that I am not understanding about Generic Singly LinkedList that is causing me to get this run time error.
Here is my code:
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)
*/
}
}
This is homework, so an explanation would be most helpful as I am sure I will be dealing with LinkedList throughout the coming months.
Since you are using the default constructor, for which you haven’t given an implementation
None of its fields are being initialized and so
Java stops execution here, but your other fields are also null. Take the time to revisit your code and initialize all the relevant fields.
The fact is you shouldn’t try to access anything in your list since you haven’t added any items to it. Its
headandcursorare null.