- 遇到一次ArrayList 移除指定下标的元素不生效的问题,先上代码:
//之前有一需求需要移除testList面指定下标的元素,指定下标存在indexList里面
List<String> indexList = Arrays.asList("3", "2", "1");
List<Integer> testList = new ArrayList<>();
testList.add(4);
testList.add(2);
testList.add(3);
testList.add(1);
indexList.forEach(e -> {
testList.remove(e);
});
testList.forEach(e->{
System.out.println("e = " + e);
});
可以看到问题并没有解决。
当时觉得很奇怪所以就看了一下remove()方法的源代码。
发现有两个同名的remove()方法,参数分别为Object类型和int类型
remove(Object) 方法是按照元素去移除的。
remove(int) 方法是按照元素移除。
因为indexList中是String类型,在执行testList.remove(e)的时候会默认调用的是remove(Object)
类型的方法所以不生效,应当改成如下代码:
List<String> indexList = Arrays.asList("3", "2", "1");
List<Integer> testList = new ArrayList<>();
testList.add(4);
testList.add(2);
testList.add(3);
testList.add(1);
for (String s : indexList) {
int index = Integer.valueOf(s).intValue();
testList.remove(index);
}
testList.forEach(e -> {
System.out.println("e = " + e);
});
只有当默认参数是int类型的时候才会按照下标移除。
Tips:一般情况是不用直接按照下标移除的,如果一定要按照下标移除应该从后往前移除,防止数字越界。