Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing an iterator for an unmodifiable list

I'm implementing an unmodifiable list based on AbstractSequentialList. Now, according to Oracle's documentation:

For an unmodifiable list, the programmer need only implement the list iterator's hasNext, next, hasPrevious, previous and index methods.

The problem is that it seems I must provide an implementation for remove, set and add methods, although these are not needed at all due the unmodifiable nature of the list, otherwise the compiler complains because these methods are not implemented.

So, am I doing something wrong or is this the real way to go? am I supposed to implement such methods and throw some kind of exception within them or so?

Thanks a lot in advance,

like image 444
Fran Marzoa Avatar asked Mar 24 '26 15:03

Fran Marzoa


2 Answers

Just throw an UnsupportedOperationException on the methods you do not need to implement. As specified by the Iterator/ListIterator interface documentation https://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#remove()

Throws: UnsupportedOperationException - if the remove operation is not supported by this list iterator

e.g.

@Override
public void remove() {
    throw new UnsupportedOperationException("Not supported yet.");
}
like image 144
d.j.brown Avatar answered Mar 26 '26 06:03

d.j.brown


http://docs.oracle.com/javase/6/docs/api/java/lang/UnsupportedOperationException.html

Thrown to indicate that the requested operation is not supported.

e.g.

@Override
public void remove() {
    throw new UnsupportedOperationException("Cannot remove from unmodifiableList");
}
like image 45
Ash Avatar answered Mar 26 '26 06:03

Ash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!