GMan
GMan

Reputation: 81

How does one change methods of an iterator?

Hey guys, I am fairly new to Java, and I have a question about collections and iterators.

In my code I have a collection (which somewhere down the road extends extends Iterable) and every object is basically a LinkedList.
I need an iterator for that collection, so I've wrote it down this way:

public class A{

     LinkedList<B> BList= new LinkedList<B>();

    ...

    public Iterator<B> iterator() {
        return BList.iterator();
    }
}

Now, the question is, how can I change any method of that iterator?
Or to be more specific, how can I disable the remove method of the iterator?

Thanks.

Upvotes: 2

Views: 380

Answers (2)

Adrian Pronk
Adrian Pronk

Reputation: 13906

You could return an iterator of an unmodifiable list:

import java.util.Collections;

...

public class A{

    LinkedList<B> BList= new LinkedList<B>();

    ...

    public Iterator<B> iterator() {
        return Collections.unmodifiableList(BList).iterator();
    }
}

This will wrap your List with an implementation that disallows any changes to the list structure (like removal). You then return an iterator based on the wrapped list.

Upvotes: 5

cadolphs
cadolphs

Reputation: 9617

If you want an unmodifiable list, use the other answer posted here. But if you want to disable only the remove, a possible way is to create a new class that extends the Iterator interface but whose remove() method throws an exception (or simply does nothing) and forwards every other method to the original iterator object:

public class MyIterator implements Iterator {
    private Iterator wrappedIterator;

    public MyIterator( Iterator it ) {
        wrappedIterator = it;
    }

    public void remove( blabla ) {
        //do nothing or raise an error, whatever floats your boat
    }

    public void otherIteratorMethod() {
        wrappedIterator.otherIteratorMethod();
    }
 }

Upvotes: 3

Related Questions