题目:存在一个集合List,需要剔除其中的值为设定值“2”的对象,如何实现
List
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
这还用想么,直接循环元素如果value等于2删除不就好了
for (int i =0; i < list.size(); i++) {
if(list.get(i).equals("2")) {
list.remove(i);
}
}
System.out.println("result" + list.toString());
也许有的人可能还会觉得这里会出现运行时异常,后面进行解释为什么不会
result [1, 3, 4, 5]
List
list.add("1");
list.add("2");
list.add("2");// 重复2的情况
list.add("3");
list.add("4");
list.add("5");
这还用想么,肯定还是直接循环元素如果value等于2删除不就好了
List
list.add("1");
list.add("2");
list.add("2");// 重复2的情况
list.add("3");
list.add("4");
list.add("5");
result [1, 2, 3, 4, 5]
呀,出bug了。。。我明明已经把为2的都进行删除了啊。
直接上源码,若想知道这是为什么就需要看看ArrayList.remove(intidex)都干了写什么
/**
* 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));
}
因此会出现现象:只移除了第一个2的问题。并且数组越界的判定为坐标是否大于等于list个数,因此并未出现运行时异常。
但是也并非所有集合如此,具体要看接口List的实现类对于remove方法的实现。
例如:假如目标题目改为如下还可以运行正常么?为什么?
List
主人公要干活去了。。。