題目:存在一個集合List,需要剔除其中的值爲設定值“2”的對象,如何實現
一、題目A
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
1.1 分析
這還用想麼,直接循環元素如果value等於2刪除不就好了
1.2 邏輯
for (int i =0; i < list.size(); i++) {
if(list.get(i).equals("2")) {
list.remove(i);
}
}
System.out.println("result" + list.toString());
也許有的人可能還會覺得這裏會出現運行時異常,後面進行解釋爲什麼不會
1.3 結果輸出
result [1, 3, 4, 5]
二、題目B
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("2");// 重複2的情況
list.add("3");
list.add("4");
list.add("5");
1.1 分析
這還用想麼,肯定還是直接循環元素如果value等於2刪除不就好了
1.2 邏輯
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("2");// 重複2的情況
list.add("3");
list.add("4");
list.add("5");
1.3 結果輸出
result [1, 2, 3, 4, 5]
呀,出bug了。。。我明明已經把爲2的都進行刪除了啊。
三、源碼分析
直接上源碼,若想知道這是爲什麼就需要看看ArrayList.remove(intidex)都幹了寫什麼
1.1 源碼
/**
* Removes the element at the specifiedposition in this list.
* Shifts any subsequentelements to the left (subtracts one from their
* indices).
*
* @param index the index of theelement to be removed
* @return the element that wasremoved from the list
* @throwsIndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
rangeCheck(index); // 數組是否越界
modCount++;
E oldValue =elementData(index); // 獲取目標元素
int numMoved = size - index- 1; // 刪除對象後面是否在存在值
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved); // 將刪除元素後面的值前移
elementData[--size] = null;// Let gc do its work
return oldValue;
}
/**
* Checks if the given index isin range. If not, throws an appropriate
* runtime exception. This method does *not* check if the index is
* negative: It is always usedimmediately prior to an array access,
* which throws anArrayIndexOutOfBoundsException if index is negative.
*/
private void rangeCheck(intindex) {
if (index >= size)
throw newIndexOutOfBoundsException(outOfBoundsMsg(index));
}
1.2 圖解
1.3 總結
因此會出現現象:只移除了第一個2的問題。並且數組越界的判定爲座標是否大於等於list個數,因此並未出現運行時異常。
但是也並非所有集合如此,具體要看接口List的實現類對於remove方法的實現。
例如:假如目標題目改爲如下還可以運行正常麼?爲什麼?
List<String> list =Arrays.asList("1","2","3","4","5");
四、主人公Iterator
主人公要幹活去了。。。