正确在遍历中删除List元素
最近在写代码的时候遇到了遍历时删除List元素的问题,在此写一篇博客记录一下。
一般而言,遍历List元素有以下三种方式:
- 使用普通for循环遍历
- 使用增强型for循环遍历
- 使用iterator遍历
使用普通for循环遍历
- public class Main {
- public static void main(String[] args) throws Exception {
- List<Integer> list = new ArrayList<>();
- for (int i = 0; i < 5; i++)
- list.add(i);
- // list {0, 1, 2, 3, 4}
- for (int i = 0; i < list.size(); i++) {
- // index and number
- System.out.print(i + " " + list.get(i));
- if (list.get(i) % 2 == 0) {
- list.remove(list.get(i));
- System.out.print(" delete");
- i--; // 索引改变!
- }
- System.out.println();
- }
- }
- }
结果如下:
使用增强型for循环遍历
- public class Main {
- public static void main(String[] args) throws Exception {
- List<Integer> list = new ArrayList<>();
- for (int i = 0; i < 5; i++)
- list.add(i);
- // list {0, 1, 2, 3, 4}
- for (Integer num : list) {
- // index and number
- System.out.print(num);
- if (num % 2 == 0) {
- list.remove(num);
- System.out.print(" delete");
- }
- System.out.println();
- }
- }
- }
结果如下:
使用iterator遍历
- public class Main {
- public static void main(String[] args) throws Exception {
- List<Integer> list = new ArrayList<>();
- for (int i = 0; i < 5; i++)
- list.add(i);
- // list {0, 1, 2, 3, 4}
- Iterator<Integer> it = list.iterator();
- while (it.hasNext()) {
- // index and number
- int num = it.next();
- System.out.print(num);
- if (num % 2 == 0) {
- it.remove();
- System.out.print(" delete");
- }
- System.out.println();
- }
- }
- }
结果如下:
使用普通for循环遍历
- public class Main {
- public static void main(String[] args) throws Exception {
- List<Integer> list = new CopyOnWriteArrayList<>();
- for (int i = 0; i < 5; i++)
- list.add(i);
- // list {0, 1, 2, 3, 4}
- for (int i = 0; i < list.size(); i++) {
- // index and number
- System.out.print(i + " " + list.get(i));
- if (list.get(i) % 2 == 0) {
- list.remove(list.get(i));
- System.out.print(" delete");
- i--; // 索引改变!
- }
- System.out.println();
- }
- }
- }
结果如下:
使用增强型for循环遍历
- public class Main {
- public static void main(String[] args) throws Exception {
- List<Integer> list = new CopyOnWriteArrayList<>();
- for (int i = 0; i < 5; i++)
- list.add(i);
- // list {0, 1, 2, 3, 4}
- for (Integer num : list) {
- // index and number
- System.out.print(num);
- if (num % 2 == 0) {
- list.remove(num);
- System.out.print(" delete");
- }
- System.out.println();
- }
- }
- }
结果如下:
使用iterator遍历
- public class Main {
- public static void main(String[] args) throws Exception {
- List<Integer> list = new CopyOnWriteArrayList<>();
- for (int i = 0; i < 5; i++)
- list.add(i);
- // list {0, 1, 2, 3, 4}
- Iterator<Integer> it = list.iterator();
- while (it.hasNext()) {
- // index and number
- int num = it.next();
- System.out.print(num);
- if (num % 2 == 0) {
- it.remove();
- System.out.print(" delete");
- }
- System.out.println();
- }
- }
- }
结果如下:
正确在遍历中删除List元素的更多相关文章
- List在遍历中删除t元素
法一:使用普通for循环遍历 注意: 1.从头开始循环,每次删除后 i 减一. 2.从尾开始循环. public class Main { public static voi ...
- java 在循环中删除数组元素
在写代码中经常会遇到需要在数组循环中删除数组元素的情况,但删除会导致数组长度变化. package com.fortunedr.thirdReport; import java.util.ArrayL ...
- ES6数组中删除指定元素
知识点: ES6从数组中删除指定元素 findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引.否则返回-1. arr.splice(arr.findIndex(item => ...
- C#实现在foreach遍历中删除集合中的元素(方法总结)
目录 方法一:采用for循环,并且从尾到头遍历 方法二:使用递归 方法三:通过泛型类实现IEnumerator 在foreach中删除元素时,每一次删除都会导致集合的大小和元素索引值发生变化,从而导致 ...
- 【坑】Java中遍历递归删除List元素
运行环境 idea 2017.1.1 需求背景 需要做一个后台,可以编辑资源列表用于权限管理 资源列表中可以有父子关系,假设根节点为0,以下以(父节点id,子节点id)表示 当编辑某个资源时,需要带出 ...
- Java集合类ArrayList循环中删除特定元素
在项目开发中,我们可能往往需要动态的删除ArrayList中的一些元素. 一种错误的方式: <pre name="code" class="java"&g ...
- 如何python循环中删除字典元素
//下面这行就是在循环中遍历删除字典元素的方法! for i in list(dictheme2.keys()): if dictheme2[i]<self.countFortheme: dic ...
- LeetCode 82,考察你的基本功,在有序链表中删除重复元素II
本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是LeetCode专题的第51篇文章,我们来看LeetCode第82题,删除有序链表中的重复元素II(Remove Duplicates ...
- python中删除某个元素的3种方法
python中关于删除list中的某个元素,一般有三种方法:remove.pop.del 1.remove: 删除单个元素,删除首个符合条件的元素,按值删除 举例说明: >>> st ...
随机推荐
- linux下的Shell编程(5)循环
Shell Script中的循环有下面几种格式: while [ cond1 ] && { || } [ cond2 ] -; do - done for var in -; do - ...
- idea中,发现某个java语法在低版本中不支持时的解决办法
比如,在某个工程中,准备用java.util.Objects#equals语法,发现提示版本不支持. F4查看Module的配置,发现原来是1.6版本. 当我手动修改为1.8时,提示我:Module是 ...
- 【第二十篇】C#微信H5支付 非微信内浏览器H5支付 浏览器微信支付
微信开发者文档 微信H5支付官方文档 请阅读清楚 最起码把所有参数看一遍 这个地方也可以看看 微信案例 http://wxpay.wxutil.com/mch/pay/h5.v2.php,请在微 ...
- Commons-FileUpload组件的应用
<% request.setCharacterEncoding("utf-8"); String uploadFileName="";//上传的文 ...
- AES(高级加密)
AES(高级加密) #3.6安装 pip3 install pycryptodome #mac pip3 install pycrypto a. 事例: ####################### ...
- tornado解决高并发的初步认识牵扯出的一些问题
#!/bin/env python # -*- coding:utf-8 -*- import tornado.httpserver import tornado.ioloop import torn ...
- filter过滤器与map映射
filter过滤器 >>> list(filter(None,[0,1,2,True,False])) [1, 2, True] filter的作用就是后面的数据按照前面的表达式运算 ...
- Canvas绘制五角星
from tkinter import * import math as m root = Tk() w = Canvas(root, width=200, height=100, backgroun ...
- 如何解释vue的生命周期才能令面试官满意?
当面试官问:"谈谈你对vue的生命周期的理解",听到这句话你是不是心里暗自窃喜:这也太容易了吧,不就是beforeCreate.created.beforeMount.mounte ...
- MySQL获取XML格式数据
通过再调用mysql工具时使用--xml选项: C:\Users\wang>mysql -uroot -p --xml mydb Enter password: ******** Welcome ...