每天一个脱发小技巧 | 使用for循环删除List元素时删除失败的解决方案

构建一个ArrayList,其元素值为1,2,3,3,4,利用for循环和list的remove()方法,删除list中所有值为3的元素
看如下一段代码:

import java.util.ArrayList;
import java.util.List;

public class ListTest {
	public static void main(String[] args) {
		List<Integer> numbers = new ArrayList<Integer>();
		numbers.add(1);
		numbers.add(2);
		numbers.add(3);
		numbers.add(3);
		numbers.add(4);
		System.out.println(numbers);// list中元素值为1, 2, 3, 3, 4
		for (int i = 0; i < numbers.size(); i++) {
			if (numbers.get(i) == 3) {// 删除list中所有值为3的数字
				numbers.remove(i);
			}
		}
		System.out.println(numbers);
	}
}

运行结果如下
在这里插入图片描述
可以发现结果中还剩下一个元素3,只有一个3被删除了,那为什么会出现这种情况呢?
我们来分析一下list的remove原理:

list API中remove部分
remove
E remove(int index)
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.
Parameters:
index - the index of the element to be removed
Returns:
the element previously at the specified position
Throws:
UnsupportedOperationException - if the remove operation is not supported by this list
IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())
移除列表中指定位置的元素(可选操作)。将任何后续元素向左移动(从它们的索引中减去1)。返回从列表中删除的元素。
参数:
index—要删除的元素的索引
返回:
先前位于指定位置的元素
抛出:
如果该列表不支持删除操作,则为UnsupportedOperationException
如果索引超出范围(索引< 0 ||索引>= size())

remove操作会移除指定位置的元素,并且将所有后续元素向左移动。因此在上文的代码中,我们使用for循环进行遍历,在移除一个位置的元素后,其后所有元素向左移动了一个位置,这将导致移除元素的下一个无法被遍历到,故此出现了上述情况出现的问题。
修改方案:
在调用remove()方法后不移动for循环。

import java.util.ArrayList;
import java.util.List;

public class ListTest {
	public static void main(String[] args) {
		List<Integer> numbers = new ArrayList<Integer>();
		numbers.add(1);
		numbers.add(2);
		numbers.add(3);
		numbers.add(3);
		numbers.add(4);
		System.out.println(numbers);// list中元素值为1, 2, 3, 3, 4
		for (int i = 0; i < numbers.size(); i++) {
			if (numbers.get(i) == 3) {// 删除list中所有值为3的数字
				numbers.remove(i);
				i--;// 新增的部分,防止i进行移动
			}
		}
		System.out.println(numbers);
	}
}

运行结果如下:
在这里插入图片描述
成功解决了删除失败的问题,除此之外还可以使用iterator迭代器方法进行删除,使用迭代器方法删除元素时不会发生这种问题,在java中我们提倡使用迭代器对list进行修改,具体的实现方法可以参看另一篇博文:
java 删除List元素的方法
里面有使用迭代器方法进行删除操作的代码实例。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值