开发者

How does one change methods of an iterator?

开发者 https://www.devze.com 2023-01-26 19:52 出处:网络
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 b

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 ques开发者_开发技巧tion 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.


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.


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();
    }
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消