java – ArrayList的特殊行为remove() – 为什么?
发布时间:2020-12-15 04:40:37  所属栏目:Java  来源:网络整理 
            导读:当我们删除-1并清空ArrayList时,它会抛出ConcurrentModificationException,当我们从同一个空ArrayList中删除0时,它会抛出NoSuchElementException. 请找到以下代码: public class Test { public static void main(String[] argv) { ArrayListInteger list =
                
                
                
            | 
                         
 当我们删除-1并清空ArrayList时,它会抛出ConcurrentModificationException,当我们从同一个空ArrayList中删除0时,它会抛出NoSuchElementException. 
  
  
请找到以下代码: 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 ");
        }
    }
} 
 从我的理解NoSuchElementException是好的,但为什么抛出ConcurrentModificationException? 解决方法
 如果检查ArrayList的代码.首先执行范围检查,然后添加修改计数. 
  
  
  
        rangeCheck(index); modCount++; 在范围检查方法中,范围检查仅适用于正数. if (index >= size)
     throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 
 因此remove(0)不会添加mod计数,但remove(-1)会添加. modCount导致迭代器抛出ConcurrentModificationException. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
相关内容
