gpt4 book ai didi

java - 如何从集合中删除数组?

转载 作者:行者123 更新时间:2023-11-29 07:02:32 26 4
gpt4 key购买 nike

我有一个 Integer[] 集合,我想从中删除一些元素,但通常的删除方法似乎不起作用。除了迭代和比较 Integer[] 的每个元素之外,还有其他解决方法吗?下面是这个问题的测试代码。

import java.util.ArrayList;
import java.util.List;


public class Test {

public static void main(String args[]){
List<Integer[]> subSet = new ArrayList<Integer[]>();
subSet.add(new Integer[]{0,1,2,3,4});
subSet.add(new Integer[]{0,1,2,3,5});
subSet.add(new Integer[]{0,0,0,0,0});
//prune this collection by removing an Integer[]
Integer[] elementToRemove = {0,0,0,0,0};
System.out.println( "Before " + subSet.size());
subSet.remove(elementToRemove);
System.out.println( "After " + subSet.size());
//
}
}

最佳答案

使用 iterator 绝对有可能。由于数组不会覆盖 equals,因此您需要静态 Arrays 方法。

 public static void main(String args[]){
List<Integer[]> subSet = new ArrayList<Integer[]>();
subSet.add(new Integer[]{0,1,2,3,4});
subSet.add(new Integer[]{0,1,2,3,5});
subSet.add(new Integer[]{0,0,0,0,0});
//prune this collection by removing an Integer[]
Integer[] elementToRemove = {0,0,0,0,0};
System.out.println( "Before " + subSet.size());

//get your Integer[] iterator
Iterator<Integer[]> it = subSet.iterator();
//for each element in the array
while(it.hasNext()){

//check if it is equal to the elementToRemove
if(Arrays.equals(it.next(), elementToRemove)){
//remove it
it.remove();
}
}
System.out.println( "After " + subSet.size());
}

关于java - 如何从集合中删除数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23848271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com