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

Inconsistent behavior on ListIterator.remove when list is reversed

XMLWordPrintable

      ADDITIONAL SYSTEM INFORMATION :
      MacOS Sequoia 15.5

      openjdk version "24" 2025-03-18
      OpenJDK Runtime Environment (build 24+36-3646)
      OpenJDK 64-Bit Server VM (build 24+36-3646, mixed mode, sharing)

      A DESCRIPTION OF THE PROBLEM :
      A list iterator created from an empty reversed list allows adding an element and subsequent removal.

      However with a ListIterator created from doubly reversed list the removal operation will fail with an IllegalStateException.

      The behavior of the ListIterator is inconsistent.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Refer to test case code

      ListIterator<Object> rev1 = new ArrayList<>().reversed().listIterator();
      rev1.add("a");
      rev1.remove(); //succeeds

      ListIterator<Object> rev2 = new ArrayList<>().reversed().reversed().listIterator();
      rev2.add("a");
      rev2.remove(); //fails with java.lang.IllegalStateException

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Java finishes without exception
      ACTUAL -
      Exception in thread "main" java.lang.IllegalStateException
      at java.base/java.util.ArrayList$Itr.remove(ArrayList.java:1063)
      at Test.main(Test.java:9)

      ---------- BEGIN SOURCE ----------
      import java.util.ListIterator;
      import java.util.ArrayList;
      import java.util.Collections;

      public class Test{
          public static void main(String [] args){
              ListIterator<Object> rev2 = new ArrayList<>().reversed().reversed().listIterator();
              rev2.add("a");
              rev2.remove();
          }
      }
      ---------- END SOURCE ----------

            pmtavare Patricia Tavares
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: