I wouldn't call Enumeration
fail-safe.
At least not the implementation returned by Vector
's elements()
method:
public Enumeration<E> elements() {
return new Enumeration<E>() {
int count = 0;
public boolean hasMoreElements() {
return count < elementCount;
}
public E nextElement() {
synchronized (Vector.this) {
if (count < elementCount) {
return elementData(count++);
}
}
throw new NoSuchElementException("Vector Enumeration");
}
};
}
This implementation can cause bad behavior without throwing an exception if you modify the Vector
while iterating over it.
For example, the following code will cause an infinite loop, in which each call to els.nextElement ()
will return the same element "a"
.
Vector<String> vec = new Vector<> ();
vec.add ("a");
vec.add ("b");
vec.add ("c");
Enumeration<String> els = vec.elements ();
while (els.hasMoreElements ()) {
System.out.println (els.nextElement ());
vec.add (0,"d");
}