【问题标题】:Error when I add or remove elements from an arraylist [duplicate]当我从数组列表中添加或删除元素时出错[重复]
【发布时间】:2021-04-08 19:28:01
【问题描述】:

我需要遍历 arrayList 并根据某些条件从中添加/删除元素。问题是,在添加/删除 arrayList 的大小更改后,我收到 Null Pointer Exception 错误。任何帮助将不胜感激。

 public class hello{
   MyArrayList<Integer> list = new MyArrayList<>();
   list.add(1);
   list.add(2);
   .......
   for (int i = 0; i < list.size(); i++){
       if(//some condition){
          list.add(//something);
       }
       else if(//some condition){
           list.remove(//something);

      }
    }
 }

【问题讨论】:

    标签: java arrays arraylist data-structures error-handling


    【解决方案1】:

    您应该使用 foreach 循环。这样,如果添加或删除元素,无论大小如何变化,您都将遍历列表中的每个元素。

    这是一个例子:

    for(Integer number : list) {
        if(number <= 1){
            list.remove(number);
        }
        else if(number >= 3) {
            list.add(number + 1);
        }
    }
    

    【讨论】:

      【解决方案2】:

      假设您的 MyArrayList 类扩展了 ArrayList,您可以使用 ListIterator 遍历列表并添加/删除元素。

      https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html

      【讨论】:

        【解决方案3】:

        您还可以使用 Stream API 并通过过滤器或映射遍历所有元素,如下所示:

        list.stream().filter(a->"some condition").map(a-> "some mapping").collect("some collector")
        

        【讨论】:

          猜你喜欢
          • 2017-09-04
          • 1970-01-01
          • 2013-04-01
          • 1970-01-01
          • 2018-09-05
          • 1970-01-01
          • 2015-01-05
          • 2017-07-25
          • 2012-05-09
          相关资源
          最近更新 更多