I'm getting a NullPointerException for the code below, and I don't quite understand why (or how to fix it). I know that my first node (next) is null, and that I can't call any methods on it without causing a null pointer exception, but I can't make it 'not null' without calling any methods on it :(. The null pointer exception is thrown in the first for loop in the insert function.
Here's my node class:
public class Node {
public Node next;
public String word;
public Node(String word){
this.word = word;
}
public void display(){
System.out.println (word);
}
public String toString(){
return word;
}
And here's my linked list class
public class WordLinkedList {
private int size; //integer to store the size of the linked list (# of words)
private Node firstnode; // reference to first node
public WordLinkedList(){
size = 0;
firstnode = new Node(null); // setting first node to null - dummy node ... I think ???!!!
}
public WordLinkedList(String[] arrayOfWords){
for (int i = 0; i < arrayOfWords.length; i++){
this.insert(arrayOfWords[i]);
}
}
public void insert(String newword){
Node newNode = new Node(newword);
for (Node iterator = firstnode.next; iterator != null; iterator = newNode.next){
if (iterator.word.compareTo(newword) < 0){
if (iterator.next.word.compareTo(newword)>0){
newNode.next = iterator.next;
iterator.next = newNode;
}
}
if (iterator.word.compareTo(newword) > 0){
iterator.next = iterator;
firstnode.next = newNode;
}
}
}
public void display(){
Node theNode = firstnode;
while (theNode != null){
theNode.display();
System.out.println("Next node: " + theNode.next);
theNode = theNode.next;
System.out.println();
}
}
}