Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8157645

Itr.hasNext() in ArrayList class is not implemented correctly

XMLWordPrintable

      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.

            psonal Pallavi Sonal (Inactive)
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: