【问题标题】:remove() metthod of ArrayList not working for ArrayList of int array (ArrayList<int[]>) in Java [duplicate]ArrayList 的 remove() 方法不适用于 Java 中 int 数组 (ArrayList<int[]>) 的 ArrayList [重复]
【发布时间】:2020-05-11 20:04:12
【问题描述】:

我正在尝试使用 ArrayList 的 remove(Object o) 来删除一个 int 数组,但这不是删除。如何用 remove(Object o) 删除 int 数组?

package remove;

import java.util.ArrayList;


public class Test{

    public static void main(String args[]) {
        ArrayList<int[]> test = new ArrayList<int[]>();
        test.add(new int[] {0,1});
        test.add(new int[] {0,2});
        test.add(new int[] {0,3});
        test.add(new int[] {0,4});
        test.add(new int[] {0,5});
        test.add(new int[] {0,6});
        test.add(new int[] {0,7});

        test.remove(new int[] {0,4});

        for(int i=0; i<test.size(); i++) {
            System.out.println(test.get(i)[0] + " " + test.get(i)[1]);
        }

    }
}

这已经结束了:

0 1
0 2
0 3
0 4
0 5
0 6
0 7

【问题讨论】:

标签: java arraylist


【解决方案1】:

因为它们是不同的对象,如果你System.out.println(new int[] {0,4}==new int[] {0,4});,结果将是false

尝试像这样删除:

public static void main(String[] args) {
    ArrayList<int[]> test = new ArrayList<>();
    test.add(new int[] { 0, 1 });
    test.add(new int[] { 0, 2 });
    test.add(new int[] { 0, 3 });
    test.add(new int[] { 0, 4 });
    test.add(new int[] { 0, 5 });
    test.add(new int[] { 0, 6 });
    test.add(new int[] { 0, 7 });
    int[] removeArr = new int[] { 0, 4 };
    test.removeIf(p -> Arrays.equals(p, removeArr));

    for (int i = 0; i < test.size(); i++) {
      System.out.println(test.get(i)[0] + " " + test.get(i)[1]);
    }
}

,输出

0 1
0 2
0 3
0 5
0 6
0 7

【讨论】:

  • 你也可以使用int[] toRemove = {0,4}; test.removeIf(a -&gt; Arrays.equals(a, toRemove));,对于更长的数组肯定会更容易写,并且可以用于可变大小的数组。
  • 如果像我展示的那样做会更好,以免创建比较{ 0, 4 }数组7次。
【解决方案2】:

您可以通过对所有测试元素运行 for 循环来找到它,并通过执行以下代码删除该元素:

public static void main(String[] args) {
    ArrayList<int[]> test = new ArrayList<int[]>();
    test.add(new int[] {0,1});
    test.add(new int[] {0,2});
    test.add(new int[] {0,3});
    test.add(new int[] {0,4});
    test.add(new int[] {0,5});
    test.add(new int[] {0,6});
    test.add(new int[] {0,7});
    for(int i=0; i<test.size(); i++) {
        if(test.get(i)[0]==0 && test.get(i)[1]==4){
            test.remove(i);
            i--;
        }
    }

    for(int i=0; i<test.size(); i++) {
        System.out.println(test.get(i)[0] + " " + test.get(i)[1]);
    }

}

祝你好运!

【讨论】:

  • 删除时需要将i递减,否则会跳过一个元素。
  • 尝试将{0,5} 更改为{0,4},这样就有两个连续的{0,4} 数组。只有其中一个会被删除,因为第二个被跳过。现在将它们中的 all 更改为 {0,4},并删除 7 个中的 4 个,留下 3 个。 --- 现在,如果您希望代码与remove(Object) 一致(删除指定元素的第一次 出现),那么您需要添加break而不是递减i。 --- 无论哪种方式,当前的代码都是有缺陷的。
  • 哇,谢谢你纠正我!我现在将编辑我的评论
猜你喜欢
  • 2012-05-15
  • 2015-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-05
  • 1970-01-01
  • 2017-08-22
  • 2021-04-07
相关资源
最近更新 更多