Skip to main content

java.util.Collections still misses unmodifiableIterator()

3 replies [Last post]
gordan
Offline
Joined: 2005-01-06

In JDK7, new methods to get empty iterators have been added, thanks.

But the (much more useful) methods:

public Iterator unmodifiableIterator(Iterator itr)
public ListIterator unmodifiableListIterator(ListIterator litr)

are still missing, have they been overseen ?

The point is, that these classes effectively already exist in the JDK as anonymous classes returned by the iterator() method of UnmodifiableCollection, so it would not make the JDK much larger by just adding the missing static methods !

The other point is that it is inefficient to create an unmodifiable collection if the only thing you need is an unmodifiable iterator. This is a new requirement caused by the introduction of the Iterable interface which no longer requires to have a Collection to get an Iterator.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
gordan
Offline
Joined: 2005-01-06

A typical example is when a class wraps a collection and implements Iterable :

/** Immutable class to provide informations about all installed applications. */
public final class ApplicationInfos implements Iterable {

private final List infos;

public ApplicationInfos(List infos) {
this.infos = new ArrayList(infos);
}

public int size() {
return infos.size();
}

public Iterator iterator() {
return Collections.unmodifiableIterator(infos.iterator()); // *********** missing
}
}

jmehrens
Offline
Joined: 2005-06-14

Using your example, you can still generate an unmodifiable iterator.

public Iterator iterator() {
return Collections.unmodifiableList(infos).iterator();
}

One of the collection guidelines is to pass collections around instead of iterators. Since you followed that guideline, you didn't require and unmodifiableIterator method.

Jason

gordan
Offline
Joined: 2005-01-06

The point is that if you just want to implement java.util.Iterable (required to be able to use the foreach() loop) you just need to provide an iterator, and not a collection.