How to implement iterator as an attribute of a class in Java
- by de3
Hi, let's say I have this simple MyArray class, with two simple methods: add, delete and an iterator. In the main method we can see how it is supposed to be used:
public class MyArray {
int start;
int end;
int[] arr;
myIterator it;
public MyArray(){
this.start=0;
this.end=0;
this.arr=new int[500];
it=new myIterator();
}
public void add(int el){
this.arr[this.end]=el;
this.end++;
}
public void delete(){
this.arr[this.start]=0;
this.start++;
}
public static void main(String[] args){
MyArray m=new MyArray();
m.add(3);
m.add(299);
m.add(19);
m.add(27);
while(m.it.hasNext()){
System.out.println(m.it.next());
}
}
And then MyIterator should be implemented somehow:
import java.util.Iterator;
public class myIterator implements Iterator{
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return false;
}
@Override
public Object next() {
// TODO Auto-generated method stub
return null;
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
}
MyIterator should iterate arr from MyArray class, from start to end values; both are also attributes of MyArray. So, as MyIterator should use MyArray attributes, how should MyIterator be implemented? Perhaps I can send the current object in the initialization:
it=new myIterator(this);
But I guess it's not the best soultion. Or maybe MyArray itself should implement Iterator interface? How is this solved?