我是編程的初學者,我需要編寫某種自己的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
然後要麼它沒有被正確添加,或者你沒有正確訪問它 –