/**
* Removes the element at the specified position in this list (optional
* operation). Shifts any subsequent elements to the left (subtracts one
* from their indices). Returns the element that was removed from the
* list.
*
* @param index the index of the element to be removed
* @return the element previously at the specified position
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this list
* @throws IndexOutOfBoundsException if the index is out of range
* (<tt>index < 0 || index >= size()</tt>)
*/
E remove(int index);
List的remove(int index)方法:移除此列表中指定位置的元素(可选操作)。将任何后续元素向左移动(从它们的索引中减去 1)。返回从列表中删除的元素。
因此正序遍历remove时注意索引减1
1、正序遍历
for (int i = 0; i < list.size(); i++)
{
int item = list.get(i);
if (item == 3)
{
list.remove(item);
i--;
}
2、倒序遍历
for (int i = list.size()-1; i >=0; i--)
{
int item = list.get(i);
if (item == 3)
{
list.remove(item);
}
}
3、使用迭代器iterator.remove()
for (Iterator<Integer> iter = list.iterator(); iter.hasNext();)
{
int item = iter.next();
if (item == 3)
{
iter.remove();
}
}
注意使用迭代器时若直接用list.remove()删除会报错:
for (Iterator<Integer> iter = list.iterator(); iter.hasNext();)
{
int i = iter.next();
if (i == 3)
{
list.remove(i);
}
}
API中此异常的解释:当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。
原因:
Iterator 是工作在一个独立的线程中,并且拥有一个 mutex 锁。 Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,所以按照 fail-fast 原则 Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。
所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。但你可以使用 Iterator 本身的方法 remove() 来删除对象, Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。