遍历List 同时 remove注意事项

    /**
     * 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 &lt; 0 || index &gt;= 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() 方法会在删除当前迭代对象的同时维护索引的一致性。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值