I am having trouble with my code to add iterator support to ArrayList this is the class i create to implement Iterator
class MyArrayListIterator<E> implements Iterator<E> {
private E[] list = null;
private int currentIndex = 0;
@Override
public boolean hasNext() {
if (currentIndex < list.length) {
return true;
} else {
return false;
}
}
@Override
public E next(){
return list[currentIndex++];
}
} This must include, which i think i did correct
"list" of type MyArrayList
"currentIndex" of type int, initially at zero
This is my main method for testing
public static void main(String[] args) throws Exception {
MyList<String> names = new MyArrayList<>();
names.add("Steve");
names.add("Frank");
names.add("Heather");
names.add("Chris");
names.add("Oliver");
for (String string : names) { // error at names Can only iterate over an array or an instance of java.lang.Iterable
System.out.println(string);
}
}
}
In the myArrayList i have added as the requirement is Make MyArrayList implement the Iterable interface by adding the iterator() method, which should return an instance of MyArrayListIterator.
public Iterator<E> iterator() {
return new MyArrayListIterator();
}
Please let me know what I am doing wrong.