I am trying to make a basic custom iterator within a class that simply iterates
ID: 3591697 • Letter: I
Question
I am trying to make a basic custom iterator within a class that simply iterates through an array but I'm having significant trouble. With what I have, my biggest trouble is the next() method; the compiler thinks the E generic is different from MyArrayList<E> class. Any help to make this work is appreciative. Please note I have three instance variable E[] list, int size and int capacity (this variable was only used for an ensureCapacity method) if this helps thank you.
public Iterator<E>iterator(){
return new myIterator<E>();
}
private class myIterator<E> implements Iterator<E>{
private int indexPosition = 0;
public boolean hasNext(){
return indexPosition < size;
}
public E next(){
E e = list[indexPosition];// wrong
++indexPosition;
return e;
}
}
Explanation / Answer
Please find my implementation.
import java.util.Iterator;
private class myIterator<Type> implements Iterable<Type> {
private MyArrayList<E> arrayList;
private int currentSize;
public myIterator(MyArrayList<E> list) {
this.arrayList = list;
this.currentSize = list.size;
}
@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;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.