let's say I have this simple MyArray class with two simple methods: add, delete, and iterator. In the main method, we see how it should 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() {
}
MyIterator must iterate arr from the MyArray class, from start to finish; both are attributes of MyArray. So, since MyIterator should use MyArray attributes, how should MyIterator be implemented? Perhaps I can send the current object to initialization:
it=new myIterator(this);
But I think this is not the best soul. Or maybe MyArray should implement the Iterator interface? How to solve this?
EDIT:
Ok, thanks everyone. This was a simple example of what I should do, so it doesn't care about a fixed-length array. Waht, I really want to make a circular FIFO, so start and end are cursors.
This round FIFO will be an array of int pairs with, for example, a size of 300: int[][] arr=new int[300][2] .
When repeating a circular array, I have to take care of whether the counter fits the end and start it from the very beginning, so this is how I solved it:
if (this.start >= this.end ) temp_end=this.end+this.buff.length; else temp_end=this.end; int ii; int j=0; int[] value=new int[2]; for(int i=this.start; i<temp_end; i++){ ii=i% this.arr.length; value=this.buff[ii];
}
But I would like not to worry about these things and just iterate over a simple way, I can do it using the iterator interface, but then I have two problems: the first of which I already explained and was solved by many answers, and the second is that my array consists of pairs of ints, and I cannot use an iterator with primitive types.