JD.NEXT

JD.NEXT occurs when an Iterator.next() is called without a preceding hasNext().

Vulnerability and risk

A 'next()' method can throw a NoSuchElement exception if there are not enough elements in the collection.

Mitigation and prevention

If an exception is expected, mark your method as throwing a java.util.NoSuchElementException. Otherwise, it is better to add an explicit check for iter.hasNext instead of collection.size(), to avoid a time-to-check time-to-use race condition. Even if you think that this method is not mult-ithreaded, it will improve the readability and maintainability of the code.

Example 1

Copy
     public boolean intersects(Set setA, Set setB) {
         for (final Iterator iteratorA = setA.iterator(); iteratorA.hasNext();) {
             final Object a = iteratorA.next();
             for (final Iterator iteratorB = setB.iterator(); iteratorB.hasNext();) {
                 Object b = iteratorA.next();
                 if (a.equals(b)) {
                     return true;
                 }
             }
         }
         return false;
     }

JD.NEXT is reported for the snippet on line 15: method 'next()' is called for 'iteratorA' without a preceding 'hasNext()' check. You may have intended to call the 'next()' method for 'iteratorB' instead of 'iteratorA'.

Example 2

Copy
     public boolean intersects(Set setA, Set setB) {
         for (final Iterator iteratorA = setA.iterator(); iteratorA.hasNext();) {
             final Object a = iteratorA.next();
             for (final Iterator iteratorB = setB.iterator(); iteratorB.hasNext();) {
                 Object b = iteratorB.next();
                 if (a.equals(b)) {
                     return true;
                 }
             }
         }
         return false;
     }

The snippet from the previous section is fixed; all calls to 'next' are preceded with appropriate 'hasNext' checks. JD.NEXT is not reported here.

Extension

This checker can be extended through the Klocwork knowledge base. See Tuning Java analysis for more information.