一個ArrayList在循環過程中刪除,會不會出問題,為什么?


ArrayList中的remove方法(注意ArrayList中的remove有兩個同名方法,只是入參不同,這里看的是入參為Object的remove方法)是怎么實現的:

	public boolean remove(Object o) {
		if (o == null) {
			for (int index = 0; index < size; index++)
				if (elementData[index] == null) {
					fastRemove(index);
					return true;
				}
		} else {
			for (int index = 0; index < size; index++)
				if (o.equals(elementData[index])) {
					fastRemove(index);
					return true;
				}
		}
		return false;
	}
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // Let gc do its work
    }

執行System.arraycopy方法,導致刪除元素時涉及到數組元素的移動。

刪除方法1:

	public static void remove(ArrayList<String> list) {
		for (int i = 0; i < list.size(); i++) {
			String s = list.get(i);
			if (s.equals("bb")) {
				list.remove(s);
			}
		}
	}

遍歷第二個元素字符串bb時因為符合刪除條件,所以將該元素從數組中刪除,並且將后一個元素移動(也是字符串bb)至當前位置,導致下一次循環遍歷時后一個字符串bb並沒有遍歷到,所以無法刪除。
倒序遍歷時即使發生元素刪除也不影響后序元素遍歷。

刪除方法2:

	public static void remove(ArrayList<String> list) {
		for (String s : list) {
			if (s.equals("bb")) {
				list.remove(s);
			}
		}
	}

modCount+1,涉及到iterator迭代。

	public E next() {
		checkForComodification();
		try {
			E next = get(cursor);
			lastRet = cursor++;
			return next;
		} catch (IndexOutOfBoundsException e) {
			checkForComodification();
			throw new NoSuchElementException();
		}
	}

調用checkForComodification()方法

	final void checkForComodification() {
		if (modCount != expectedModCount)
			throw new ConcurrentModificationException();
	}

使用迭代器就會避免這種情況:

Iterator<String> it = list.iterator();  
    while (it.hasNext()) {  
        String s = it.next();  
        if (s.equals("bb")) {  
            it.remove();  
        }  
    }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM