ArrayList集合中在遍历集合时,删除了集合中的元素,会不会对遍历产生影响呢?如果会,该怎么解决?
比如我们现在有一道这样的题:
有如下员工信息:
复制代码
1
2
3
4
5
6姓名:张三,工资:3000 姓名:李四,工资:3500 姓名:王五,工资:4000 姓名:赵六,工资:4500 姓名:田七,工资:5000
先需要将所有的员工信息都存入ArrayList集合中,并完成如下操作:
1、判断是否有姓名为“王五”的员工,如果有,改名为“王小五”
2、判断是否有姓名为“赵六”的员工,如果有,将其删除
3、给姓名为“田七”的员工,涨500工资
其他的功能倒是没什么问题,就是在遍历时删除元素经常会出问题。参考以下代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27import java.util.ArrayList; import java.util.Iterator; public class Homework3 { public static void main(String[] args) { ArrayList<Employee> arrayList = new ArrayList<>(); Employee e1 = new Employee("张三", 3000); Employee e2 = new Employee("李四", 3500); Employee e3 = new Employee("王五", 4000); Employee e4 = new Employee("赵六", 4500); Employee e5 = new Employee("田七", 5000); arrayList.add(e1); arrayList.add(e2); arrayList.add(e3); arrayList.add(e4); arrayList.add(e5); for (Employee employee : arrayList) { if (employee.getName().equals("王五")) { employee.setName("王小五"); } if (employee.getName().equals("赵六")) { arrayList.remove(employee); } if (employee.getName().equals("田七")) { employee.setSalary(5500); } }
增强for循环是会出现错误的。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14for (int i = arrayList.size() - 1; i >= 0; i--) { Employee e = arrayList.get(i); if (e.getName().equals("王五")) { e.setName("王小五"); } if (e.getName().equals("赵六")) { arrayList.remove(e); } if (e.getName().equals("田七")) { e.setSalary(5500); } }
for i 递减是解决问题的一种方法。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14Iterator<Employee> iterator = arrayList.iterator(); while (iterator.hasNext()) { Employee em = iterator.next(); if (em.getName().equals("王五")) { em.setName("王小五"); } if (em.getName().equals("赵六")) { iterator.remove(); } if (em.getName().equals("田七")) { em.setSalary(5500); } }
使用迭代器的 remove 方法是解决问题非常好的方法。
最后
以上就是活泼太阳最近收集整理的关于面试考点:ArrayList 循环遍历时删除元素问题的全部内容,更多相关面试考点:ArrayList内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复