I've stumbled upon a bug in the Java Collections API, in Collections.java.
Here’s the code verbatim from the JDK’s source. Just so you know, the JavaDoc version tag reads "1.106, 04/21/06". The method is located in line 638.
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (next.compareTo(candidate) > 0)
candidate = next;
}
return candidate;
}
If you take a second to analyse the method, you’ll quickly spot the bug: T candidate = i.next(). D’oh! Calling i.next() on an Iterator without checking hasNext() first? That’s just asking for an exception.
Surely something like that should've been spotted during coding? It means use of the API must check if the collection has at least two elements.