Answer the question
In order to leave comments, you need to log in
How to implement an Iterator for your own List?
There is a native implementation of List in Java
class List<T> implements Iterable<T> {
// code is here ...
public Iterator<T> iterator() {
// что нужно сюда писать?
}
class Node<T>{
T value;
Node<T> next;
// interface of Node is here.
}
}
Iterator<T> implements java.util.Iterator<T>{}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private Node<T> current = first;
@Override
public boolean hasNext() {
return current.hasNext();
}
@Override
public T next() throws IndexOutOfBoundsException {
T result = current.value;
if (!current.hasNext()) throw new IndexOutOfBoundsException("End of list.");
current = current.next;
return result;
}
};
}
Answer the question
In order to leave comments, you need to log in
Yes, you need to implement a class from Iterator and return an instance of that class in the iterator method. If you don’t want to bother, then you can immediately implement Iterator in your List, respectively, return this in iterator() and immediately add next, hasNext methods to it. Thus, you will have all the logic hidden in one class, but the object will be both iterable and iterator at the same time, which is not very good in my opinion.
Here is the implementation for the first link in Google:
import java.util.Iterator;
public class SOList<Type> implements Iterable<Type> {
private Type[] arrayList;
private int currentSize;
public SOList(Type[] newArray) {
this.arrayList = newArray;
this.currentSize = arrayList.length;
}
@Override
public Iterator<Type> iterator() {
Iterator<Type> it = new Iterator<Type>() {
private int currentIndex = 0;
@Override
public boolean hasNext() {
return currentIndex < currentSize && arrayList[currentIndex] != null;
}
@Override
public Type next() {
return arrayList[currentIndex++];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
return it;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question