UPD: This post is no help at all. My question is not about what is NullPointerException. I have asked with hope that someone will show me, what am I missing in in my Iterator class, so it gets a null refference. I suppose you should unmark my question so I can get an answer to my very question.
I decided to make my own implementation of one-way linked list without any java built-in classes or interfaces. At first, I created classes MyList and Nodes, and implemented some functionality for MyList, such as: adding new element to the end of the list, removing some element, checking, if the list contains some element, etc. It worked just well, you can see the whole project here.
After that I thought I'm gonna need the iterator to go through the list. So, i have writted this class:
public class Iterator<T> {
private Node currentValue;
private MyList list;
public Iterator(MyList list)
{
this.list = list;
this.currentValue = null;
}
public T next()
{
if (!list.isEmpty())
{
if (currentValue == null) currentValue = list.head;
else currentValue = currentValue.next;
return (T) currentValue.value;
}
return null;
}
public boolean hasNext()
{
if (currentValue.next.equals(null)) return false;
return true;
}
}
I think the code of the Node would be useful here:
public class Node<T> {
public T value;
public Node next;
public Node(T value)
{
this.value = value;
}
}
Then, I've made a class for execution of the program:
public class ExecutiveClass {
public static void main(String[] args)
{
MyList<Integer> list = new MyList<Integer>();
list.add(5);
list.add(10);
list.add(15);
list.add(20);
list.add(60);
System.out.println(list.containts(10));
System.out.println(list.containts(50));
Iterator iterator = new Iterator(list);
while(iterator.hasNext())
{
System.out.println(iterator.next());
}
}
}
And it seems like my Iterator doesn't work properly, because I've got this for output:
true
Exception in thread "main" java.lang.NullPointerException
false
at com.my.list.model.Iterator.hasNext(Iterator.java:40)
at com.my.list.engine.ExecutiveClass.main(ExecutiveClass.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Process finished with exit code 1
So, how do I fix the Iterator, so it will work as expected?