前言
面试时经常遇到问你:怎么删除列表中的数据?
没有遇到过for循环遍历list删除数据坑的。第一反应就是1.使用for循环遍历删除匹配数据 2.使用iterator迭代器删除数据
一、使用for循环遍历删除匹配数据(标准的错误答案)
上代码:
List<String> a = new ArrayList<>();
a.add("1");
a.add("2");
System.out.println(a);
for (String temp : a) {
if ("2".equals(temp)) {
a.remove(temp);
}
}
System.out.println(a);
打印结果:
报错原因:方法被调用一次,modCount增加一次,未重新赋值,导致后面计算数组长度不一致
二、使用iterator迭代器删除数据(正确答案)
上代码:
List<String> a = new ArrayList<>();
a.add("1");
a.add("2");
System.out.println(a);
Iterator<String> iterator = a.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
if ("2".equals(next)) {
iterator.remove();
}
}
System.out.println(a);
打印结果:
未报错原因:在调用集合iterator方法时,返回内部类Iterator实例是,迭代器中的expectedModCount会被赋为modCount的值为初始值