Java Collections API Bug?

I stumbled upon collections An error in the Java collections API in Java

The following is the code in the JDK source code As you know, the Javadoc version is marked "1.106,04 / 21 / 06" This method is on 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 moment to analyze the method, you will soon find an error: t candidate = i.next() D: Oh! Call i.next() on the iterator without first checking hasnext()? That's just an exception

Of course, you should find something similar in the coding process? This means that using the API, you must check whether the collection contains at least two elements

Solution

No - this means that trying to find the largest element of an empty collection is invalid This is specified in the API documentation:

Throws:
    NoSuchElementException - if the collection is empty.

If there is no next element, it is iterator Next () is recorded as something thrown, so it is completing its intention

Note that after calling next () for the first time, call hasNext () to check if there are multiple elements.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>