Java – the special behavior of ArrayList remove () – why?
•
Java
When we delete - 1 and empty the ArrayList, it will throw concurrentmodificationexception. When we delete 0 from the same empty ArrayList, it will throw NoSuchElementException
Please find the following code:
public class Test { public static void main(String[] argv) { ArrayList<Integer> list = new ArrayList<Integer>(); Iterator<Integer> it = list.iterator(); try { list.remove(-1); } catch (indexoutofboundsexception e) { } try { it.next();// Throwing ConcurrentModificationException } catch (ConcurrentModificationException e) { System.err.println("ConcurrentModificationException 1"); } catch (NoSuchElementException e) { System.err.println("NoSuchElementException 1 "); } list = new ArrayList<Integer>(); it = list.iterator(); try { list.remove(0); } catch (indexoutofboundsexception e) { } try { it.next();// Throwing NoSuchElementException } catch (NoSuchElementException e) { System.err.println("NoSuchElementException 2"); } catch (ConcurrentModificationException e) { System.err.println("ConcurrentModificationException 2 "); } } }
From my understanding, NoSuchElementException is good, but why throw concurrentmodificationexception?
Solution
If you check the code of ArrayList First perform a range check and then add a modification count
rangeCheck(index); modCount++;
In the range check method, the range check applies only to positive numbers
if (index >= size) throw new indexoutofboundsexception(outOfBoundsMsg(index));
Therefore, remove (0) does not add the mod count, but remove (- 1) does Modcount causes the iterator to throw a concurrentmodificationexception
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码