JDK-8157645 : Itr.hasNext() in ArrayList class is not implemented correctly
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 8u92
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: generic
  • CPU: generic
  • Submitted: 2016-05-23
  • Updated: 2016-05-24
  • Resolved: 2016-05-24
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
java version "1.8.0_77"
Java(TM) SE Runtime Environment (build 1.8.0_77-b03)
Java HotSpot(TM) 64-Bit Server VM (build 25.77-b03, mixed mode)

ADDITIONAL OS VERSION INFORMATION :
ubuntu 14.04

A DESCRIPTION OF THE PROBLEM :
Current hasNext implementation is :
        public boolean hasNext() {
            return cursor != size;
        }

It should be instead:
        public boolean hasNext() {
            return cursor < size;
        }

please check while loop is executing 2 times for the single element :-

        List<String> list=new ArrayList<>();
        list.add("Himanshu");  //added only single item
        Iterator<String> itr=list.iterator();
        while (itr.hasNext()){
            String s =itr.next();
            list.remove();   // after this size is getting changed to 0.
        }
Explanation:-
In 2nd loop of while loop statement "cursor != size" in hasNext() giving true as "cursor is 1 and size is now 0" , which is incorrect, it should not have gone in while loop in 2nd time.
and should not have thrown ConcurrentModificationException in case of single element ArrayList

Note:-
I know the remove() inside Iterating while loop is dangerous but still the behavior should remain consistent.
For Example: In two Element ArrayList the above loop does not throws the ConcurrentModificationException.

        List<String> list=new ArrayList<>();
        list.add("Himanshu");  //added two elements in List
        list.add("khantwal");
        Iterator<String> itr=list.iterator();
        while (itr.hasNext()){
            String s =itr.next();
            list.remove();   // after this size is getting changed to 1.
        }

Explanation: as size got changed to 1 and cursor is also 1 it will not go to while loop in 2nd time, as hence no ConcurrentModificationException in ArrayList of size 2


REGRESSION.  Last worked in version 8u77


REPRODUCIBILITY :
This bug can be reproduced always.


Comments
This is a duplicate of JDK-6687277.
24-05-2016