4

I am deleting 2nd last element of an ArrayList while iterating the same list through enhanced for-loop and I was expecting a ConcurrentModificationException however it is working fine. Kindly help me if java has provided a special case for 2nd last element.

I tried it with different indexes but it is working as expected only for the 2nd last element, it is giving unexpected result

    List<Integer> list=new ArrayList<>();
    list.add(2);
    list.add(4);
    list.add(3);
    list.add(5);
    for(Integer num:list) {
        if(num==3) {
            list.remove(num);
        }
        System.out.println(num);
    }

Expected result: ConcurrentModificationException

Actual Result: Working fine

9
  • 1
    The method that throws ConcurrentModificationException is the method Iterator#next that is being used with the syntax suggar for(Integer num : list) that will be actually replaced by Iterator<Integer> it = list.iterator(); while(it.hasNext()) num = it.next() there's something about hasNext returning false in the first situation. IDK Commented Jul 23, 2019 at 16:33
  • 1
    I agree that this is covered in stackoverflow.com/q/14673653/3182664 , and specifically the technical reason is explained in sufficient details in stackoverflow.com/a/14674151/3182664 (i.e. not the accepted answer there). I'll close this one as a duplicate. If there are objections, drop me a note. Commented Jul 23, 2019 at 16:35
  • @Marco13 This question is not the same,can you add your answer for it Commented Jul 23, 2019 at 16:37
  • it is definitively hasNext returning false before next can be called to throw the exception - just seen on debugger - the catch is that the for-each loop is transformed to a while loop using that methods Commented Jul 23, 2019 at 16:37
  • FWIW, according to my tests using JDK 12.0.1, it doesn't matter how long the List is, i.e. how many elements it contains, removing any element except for the second-last element throws ConcurrentModificationException. Commented Jul 23, 2019 at 16:40

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.