2

I know that in ArrayList, the iterators returned by this class's iterator and listIterator methods are fail-fast.

So if i write something like below. Since I am using List object to remove rather than using Iterator's remove so it throw's concurrentModification exception as in that case expectedModCount is not equal ModCount.

    List<String> n = new ArrayList<String>();
    n.add("1");
    n.add("2");
    n.add("3");
    n.add("4");


    Iterator<String> i = n.iterator();
    while(i.hasNext())
    {
        String t = i.next();
        if(t.equals("4"))
            n.remove(t);
        System.out.println(t);

    }

But if you remove the second last element in the list, then the exception is not thrown. I.e if you write (in the if statement, t.remove("1") or t.remove("2") or t.remove("4") ) it throws concurrentModificationException.But if I write t.remove("3"), then this exception is not thrown.

What could be the reason?

tashuhka
  • 5,028
  • 4
  • 45
  • 64
Sumit Kumar Saha
  • 799
  • 1
  • 12
  • 25

1 Answers1

0

There is a field called modCount in AbstractList, that store the number of times this list has been structurally modified, and an inner class called Itr that implements Iterator created a variabled called expectedModCount which is initialized in the beginning with modCount. The concurrentModificationException is thrown when during iteration modCount!=expectedModCount
Here is the code

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }
sol4me
  • 15,233
  • 5
  • 34
  • 34