如何从集合中删除数组?

时间:2014-05-24 18:17:52

标签: java collections

我有一个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());
        //
    }
}

2 个答案:

答案 0 :(得分:5)

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());
    }

答案 1 :(得分:1)

试试这个解决方案,它运行正常:

IntegerArray类:

public class IntegerArray {

    public final Integer[] array;

    public IntegerArray(Integer... array) {
        this.array = array;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof IntegerArray) {
            return Arrays.equals(this.array, ((IntegerArray) o).array);
        }
        return false;
    }

}

测试类:

public class Test {

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