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

hasNext returns wrong value when iterating on empty ArrayList

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 8u45
    • core-libs

      FULL PRODUCT VERSION :
      java version "1.8.0_45"
      Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
      Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

      ADDITIONAL OS VERSION INFORMATION :
      Mac OS Yosemite:
      Darwin amgdh077.o.aist.go.jp 14.3.0 Darwin Kernel Version 14.3.0: Mon Mar 23 11:59:05 PDT 2015; root:xnu-2782.20.48~5/RELEASE_X86_64 x86_64 i386 MacPro6,1 Darwin


      A DESCRIPTION OF THE PROBLEM :
      hasNext() sometimes returns the wrong value (true instead of false) when called on an empty ArrayList under certain conditions.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      (1) create a new ArrayList
      (2) add one element to that list
      (3) obtain an iterator on the list
      (4) call it.next(); even though the list is later made empty, this step is necessary for the bug to occur
      (5) make the list empty by calling remove(0) or clear()
      (6) the next call to hasNext() returns true but should return false

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      hasNext should return false
      ACTUAL -
      hasNext returns true

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      import java.util.Iterator;
      import java.util.ListIterator;
      import java.util.ArrayList;
      import java.util.LinkedList;
      import java.util.ConcurrentModificationException;
      import java.util.NoSuchElementException;

      public class hasNextBug {

        public static void main(String[] argv) {

          ArrayList<Integer> testArrayList = new ArrayList<Integer>();//ArrayList

          testArrayList.add(1);
          ListIterator it = testArrayList.listIterator();
          System.out.println("Expected result : 1... next == " + it.next());//Without this next, no bug
          System.out.println("Expected result : false... hasNext == " + it.hasNext());
          testArrayList.remove(0);
          //testArrayList.clear(); //same result as remove(0)
          System.out.println("Expected result : false... hasNext == " + it.hasNext());
          System.out.println("Expected result : ConcurrentException... next == " + it.next());
        }
      }

      /* Last call to hasNext returns wrong value. Call to next throws ConcurrentException as expected. */
      ---------- END SOURCE ----------

            psandoz Paul Sandoz
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: