-
Enhancement
-
Resolution: Fixed
-
P3
-
1.3.1
-
beta3
-
sparc
-
solaris_8
-
Verified
Name: boT120536 Date: 07/30/2001
java version "1.3.1"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1-b24)
Java HotSpot(TM) Client VM (build 1.3.1-b24, mixed mode)
The toString() method in AbstractCollection.java uses an iterator to move
through the collection but checks an arbitrary index against the collections
size() instead of using the iterators hasNext() method to determine when to
stop:
public String toString() {
StringBuffer buf = new StringBuffer();
Iterator e = iterator();
buf.append("[");
int maxIndex = size() - 1;
for (int i = 0; i <= maxIndex; i++) {
buf.append(String.valueOf(e.next()));
if (i < maxIndex)
buf.append(", ");
}
buf.append("]");
return buf.toString();
}
The problem I have is that I have my own iterator that iterates over a
collection and skips some elements. The hasNext() method only returns true if
there are more "interesting" elements in the collection. I end up getting a
NoSuchElementException because the toString above keeps calling next() even
though hasNext() would return false if it were called. Note that the spec for
next() is to throw this exception if it is called when there are no more
elements in the iteration.
I suppose it is somewhat questionable whether an iterator should skip some
elements in the collection it is iterating over. If the above toString was using
hasNext()/next() properly it would then NOT display some elements of the
collection which could probably also be considered a problem.
(Review ID: 127993)
======================================================================