I'm a beginner in programming and I need to write some kind of own LinkedList, but only with add(E element)
method and with Iterator's hasNext()
and next()
. Here is my code:
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;
}
}
}
But when I started to test add(E value)...
@Test
public void test() {
LinkedArray<String> arr = new LinkedArray<>();
String string = "Test";
arr.add(string);
String result = arr.next();
assertThat(result, is("Test"));
}
...I only get an error. What the problem is, why am I getting it wrong?