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

hasNext() needs to be made more robust

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P2 P2
    • None
    • 6u6
    • core-libs
    • None
    • generic
    • generic

      There is a bug in AbstractList in private class Itr

      method : hasNext()

      public boolean hasNext() {
                  return cursor != size();
      }

      ------------------
      It should be:
      return cursor < size();

      Below is some sample code that exercises the problem.

      I create a List with 2 elements and remove the second element.
      When I step into hasNext() in a debugger
      cursor == 2 and size == 1

      Thus hasNext() should return false. It obviously is supposed to return true if the cursor is less than the size. It returns true -- even though it does not "has Next".

      Granted -- the code is terrible. It removes an item from the list instead of removing it from the iterator. But it was nevertheless introduced into production code.
      Just changing "!=" to "<" will make AbstractList more robust.

      package quickie;
      import java.util.*;
      /**
       *
       * @author bnevins
       */
      public class Main
      {
          Main() {
              
          }
          public static void main(String[] args)
          {
              List<String> list = new ArrayList<String>();
              list.add("a");
              list.add("b");
              
              Iterator iter = list.iterator();
              while(iter.hasNext())
              {
                  String s = (String)iter.next();
                  if(s.equals("b"))
                      list.remove(s);
              }
          }
         }

            sherman Xueming Shen
            wnevins W Byron Nevins (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: