Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement iterator as an attribute of a class in Java

Tags:

java

iterator

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?

EDIT:

Ok, thanks to everybody. This was a simple example of what I wnat to do, so don't care about fixed length array. Waht I really want to do is a circular FIFO, that's why start and end are the cursors.

This circular FIFO will be an array of pairs of ints with, e.g., size 300: int[][] arr=new int[300][2].

When iterating a circular array I have to take care if the counter arrives to the end and make it start from the beginning, so this is how I have 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]; 
    //do anything with value

}

But I would like to avoid worrying about these things and just iterate in a simple way, I can do this with iterator interface, but then I have 2 problems: the first one I already explained and has been solved by many answers, and the second one is that my array is made of pairs of ints, and I can't use iterator with primitive types.

like image 323
de3 Avatar asked Dec 04 '22 10:12

de3


1 Answers

Its very unusual to maintain an iterator as an instance variable of the class. You can only traverse the array once - probably not what you want. More likely, you want your class to provide an iterator to anyone that wants to traverse your array. A more traditional iterator is below.

Java 5+ code - I haven't tried to compile or run, so it may be contain errors (not near a dev machine right now). It also uses autobox'ing for converting Integer to int.

public class MyArray implements Iterable<Integer> {

    public static class MyIterator implements Iterator<Integer> {

        private final MyArray myArray;
        private int current;

        MyIterator(MyArray myArray) {
            this.myArray = myArray;
            this.current = myArray.start;
        }

        @Override
        public boolean hasNext() {
            return current < myArray.end;
        }

        @Override
        public Integer next() {
            if (! hasNext())   throw new NoSuchElementException();
            return myArray.arr[current++];
        }

        @Override
        public void remove() {
            // Choose exception or implementation: 
            throw new OperationNotSupportedException();
            // or
            //// if (! hasNext())   throw new NoSuchElementException();
            //// if (currrent + 1 < myArray.end) {
            ////     System.arraycopy(myArray.arr, current+1, myArray.arr, current, myArray.end - current-1);
            //// }
            //// myArray.end--;
        }
    }

    ....

    // Most of the rest of MyArray is the same except adding a new iterator method ....

    public Iterator<Integer> iterator() {
        return new MyIterator();
    }

    // The rest of MyArray is the same ....

}

Also note: be careful of not hitting that 500 element limit on your static array. Consider using the ArrayList class instead if you can.

like image 62
Bert F Avatar answered Feb 23 '23 08:02

Bert F