Reputation: 101
I'm still a beginner in Java - I'm trying to create a method that finds the value of the last item in a linked list, and it's throwing a java.lang.NullPointerException
error, and it indicates the error is on line 21. From my understanding, a null pointer exception happens when the programmer is calling a reference-type variable to reference basically nothing, since the variable hasn't been declared yet.
For example, if I write Integer k;
, I cannot call on k
until I declare: k = new Integer(10);
. If I write int k;
, Java automatically sets the value to 0, since it's a primitive type, and I will be able to call it directly.
In this case, I kind of understand why it's throwing this error, since as you can see in the second line of the getLast()
method, I called next, which should be null
, since it hasn't been declared yet. However, it's indicating that the error is on line 21, where I reassign last
. Why?
How do I fix this code? FYI this is just a practice problem through my school's website, and the task was to complete the getLast()
method.
/*
* Class for representing a linked list of ints.
*/
public class List {
public int value;
public List next;
public List(final int setValue) {
value = setValue;
}
/**
* Return the value of the last item in the list.
*/
public int getLast() {
List current = next;
int last = next.value;
while(next != null) {
current = next;
next = current.next;
last = next.value; //ERROR
}
return last;
}
}
Upvotes: 0
Views: 1099
Reputation: 17900
You should move the statement that moves to the last node as the last statement of the while loop so that on the next iteration, the loop condition would become false and the loop terminates. In your case, you try to access the next
element after you reach the end of the list.
Also, you must use the local variable current
for iterating and not assign / change the instance variable next
. If you call getLast
the next time, it won't work because next
now points to null
.
Change it as
List current = next;
int last = value;//Set to the current value to begin with
while(current != null) {
last = current.value;
current = current.next;
}
return last;
Upvotes: 1
Reputation: 2406
NullPointerException
is thrown because next
is null
and you reference next.value
.
You should not change next
, use a temporary value to iterate to the end of the list.
public int getLast() {
if (next == null)
return value;
List current = next;
while (current.next != null)
current = current.next;
return current.value;
}
Upvotes: 0
Reputation: 106
When the while loop gets to the last node you set next to null with:
next = current.next
You should be able to fix by setting last = current
instead of next.
But you should be careful about empty lists. It seems that if you called getLast() on an empty list you'd have a NullPointerException again.
Upvotes: 0