【问题标题】:Simple ArrayList.remove(int) doesn't work. What I am doing wrong?简单的 ArrayList.remove(int) 不起作用。我做错了什么?
【发布时间】:2020-07-03 13:43:33
【问题描述】:

我正在尝试遍历 ArrayList 并在某些条件下(x == 0)删除实际对象(索引 s)。如果执行,它总是在应该删除对象的行处给出错误。没有remove(),它运行得很好。

int s = 0;
int x = 0;
if (!objectList.isEmpty()) {
    for (obj actualObj : objectList) {
        if (x == 0) {
            objectList.remove(s);
        } else {
            System.out.println("x != 0");
        }
        s++;
    }
} else {
    System.out.println("list is empty");
}

【问题讨论】:

标签: java loops arraylist


【解决方案1】:

我最大的挑剔是:当使用增强的 for-each 循环 (for (T val : Iterable<T>)) 之类的语法糖时,您不能改变/修改您正在迭代的集合(在调用 Iterator#remove 等之外)。事实上,Iterator#remove 的存在正是因为这个原因:

int toRemove = 0; //The number to remove from your list
List<Integer> list = /* your list */;
Iterator<Integer> itr = list.iterator(); //Create an iterator of the collection
while (itr.hasNext()) { //while new elements are available...
    Integer val = itr.next(); //grab the next available element
    if (val == toRemove) { //removal condition
        itr.remove(); //remove the last grabbed element from the collection
    }
}

如果您能够使用 Java 8:

int toRemove = 0; //The number to remove from your list
List<Integer> list = /* your list */;
list.removeIf(val -> toRemove == val); //didn't use member reference, for clarity reasons

【讨论】:

    【解决方案2】:

    您在遍历列表时将其从列表中删除。一个可行的选择是

        int x = 0;
        List<String> objectList = Arrays.asList("A", "B", "C");
        if (objectList.isEmpty()) System.out.println("list is empty");
    
        List<String> filtered = objectList.stream().filter(s1 -> x != 0).collect(Collectors.toList());
        System.out.println(objectList + "\n" + filtered);
    

    【讨论】:

      【解决方案3】:

      每次使用索引从List 中删除一个元素时,List 都会缩小,因为随后的元素会向左/向下移动一个位置。这意味着在循环的下一次迭代中,您实际上将删除一个位于最后一个已删除元素的下一个元素的元素。

      因此,您应该在循环中使用Iterator 而不是索引从List 中删除元素,如下所示:

      Iterator<YourType> itr = objectList.iterator();
      while (itr.hasNext()) {
          YourType obj = itr.next();
          if (some condition) {
              itr.remove();
          }
          // ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-13
        • 1970-01-01
        • 1970-01-01
        • 2013-05-16
        • 2017-02-09
        • 1970-01-01
        相关资源
        最近更新 更多