zoukankan      html  css  js  c++  java
  • java 中list进行动态remove处理

    java中遍历 list遇到需要动态删除arraylist中的一些元素 的情况

    错误的方式

    for(int i = 0, len = list.size(); i < len; i++){  
        if(list.get(i) == 1) {  
           list.remove(i);  
        }  
    }  

    这样会抛出异常

    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3  
        at java.util.ArrayList.RangeCheck(Unknown Source)  
        at java.util.ArrayList.get(Unknown Source

    这个异常是因为删除元素之后未改变相应角标,遍历到最后一个 的时候 就会找不到抛出 这个异常

    正确做法删除下标以及定位到遍历位置

    for(int i = 0, len = list.size(); i < len; i++){  
        if(list.get(i) == 1){  
           list.remove(i);  
           len--;
           i--;
        }  
    }

    或者使用Java的Iterator接口来实现遍历

    Iterator<Integer> iterator = list.iterator();  
    while(iterator.hasNext()){  
        int i = iterator.next();  
        if(i == 1){  
            iterator.remove();  
        }  
    }
  • 相关阅读:
    Python正课132 —— Vue 进阶5
    Python正课131 —— Vue 进阶4
    Python正课130 —— Vue 进阶3
    logging模块
    作业20
    suprocess模块
    configparser模块
    hashlib模块
    shutil模块
    序列化模块
  • 原文地址:https://www.cnblogs.com/dashuai01/p/7823387.html
Copyright © 2011-2022 走看看