Re: returning a pair of iterator.
"toton" <abirbasak@gmail.com> wrote in message
news:1159969205.595764.187530@b28g2000cwb.googlegroups.com...
I want the list element not to get modified (with or without iterator).
Something like C++ const_iterator. Can it be done directly or
indirectly?
Have your elements implement some sort of interface which provides all
the "getter" and non mutating functionality, and have the iterator wrap the
elements in an immutable wrapper (or copy):
interface Foo {
public int getX();
}
class MutableFoo implements Foo {
private int myX;
public int getX() {
return myX;
}
public void setX(int newValue) {
myX = newValue;
}
}
class ImmutableFoo implements Foo {
private final int myX;
public ImmutableFoo(int value) {
myX = value;
}
public ImmutableFoo(Foo value) {
myX = value.getX();
}
public int getX() {
return myX;
}
}
class ConstIterator<Foo> implements Iterator<Foo> {
private final Iterator<Foo> delegateIterator;
public ConstIterator<Foo>(Iterator<Foo> delegate) {
delegateIterator = delegate;
}
public boolean hasNext() {
delegateIterator.hasNext();
}
public Foo next() {
return new ImmutableFoo(delegateIterator.next());
}
public void remove() {
/*I don't know what C++'s const_iterator does here, but you should be
able to figure it out from here on.*/
}
}
Note that a really determine programmer can still modify the elements
using sneaky stuff like reflection or JNI.
- Oliver