Jazzy Jazzy - 2 months ago 8
Java Question

Implementing an iterator for a immutable data type

For my current university course we are required to implement an Iterator for an immutable data type. So far so good, nothing too dificult, here is what it looks like:

public Iterator<T> iterator(){
return new Iterator<T>() {
private int index = 0;

@Override
public boolean hasNext() {
//hasNext implementation
}

@Override
public T next() {
//Next Implementation
}
};


I used a mutable variable (index) that points to the current position in the data type. The exercise requires us to make every member variable final (makes sense for an immutable data type), but it also requires us to make every member variable in the iterator final (index). This is what makes me confused, because I dont see a way of iterating over a data type without a mutable variable, especially because you cant change the iterator from inside of the next() method...
I dont want a solution to the problem, I just want to know, wether or not this is possible and maybe a slight hint to a solution... Thanks!

Answer Source

If making every member variable final is your requirement, you could make index into an array:

public Iterator<T> iterator(){
    return new Iterator<T>() {
      private final int[] index = {0};
      // ...
    };
}

because array elements remain are mutable, even if the reference to it is final. But this just makes the code messier, because of using index[0] everywhere instead of just index.

Iterators are inherently mutable; there's no way I can think of to make them immutable, since you want them to change as you use them.


Note that simply making all member variables final does make a type immutable. The member variables must also refer to deeply-immutable objects; non-zero length arrays cannot be deeply immutable, since you can always reassign their elements.