我是编程的初学者,我需要编写某种自己的LinkedList,但只能用add(E element)
方法和Iterator的hasNext()
和next()
。这里是我的代码:NPE自己实现的LinkedList(Java)
public class LinkedArray<E> implements Iterator<E> {
private int size = 0;
private int current = 0;
private Node<E> first;
private Node<E> last;
private Objects[] objects = new Objects[10];
public void add(E value) {
Node<E> element = new Node<E>(last, value, null);
if (last != null) {
element.next = element;
} else {
first = element;
}
last = element;
size++;
}
@Override
public boolean hasNext() {
boolean result = false;
try {
if (objects[current + 1] != null) {
result = true;
}
} catch (ArrayIndexOutOfBoundsException e) {
result = false;
}
return result;
}
@Override
public E next() {
E result;
try {
current++;
result = (get(current - 1));
} catch (ArrayIndexOutOfBoundsException a) {
throw new NoSuchElementException("No more elements in list.");
}
return result;
}
public E get(int position) throws NullPointerException {
Object result;
if (this.objects[position] != null) {
result = this.objects[position];
} else {
throw new NullPointerException("Position is empty.");
}
return (E) result;
}
private class Node<E> {
private E element;
private Node<E> next;
private Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
}
但是当我开始测试添加(E值)...
@Test
public void test() {
LinkedArray<String> arr = new LinkedArray<>();
String string = "Test";
arr.add(string);
String result = arr.next();
assertThat(result, is("Test"));
}
...我只能得到一个错误。问题是什么,为什么我错了?
发布错误(stacktrace)你正在得到 – hanumant
@hanumant它只是“java.lang.NullPointerException:位置为空。”在E get(int position)方法中。 – blackHorsie
然后要么它没有被正确添加,或者你没有正确访问它 –