2

I have a list<array[]> in Java, and I want to remove from it all duplicates.

In addition, the array [1,2] is the same as array [2,1].

I want to use Set, but as I understand it, if I declare 2 arrays: int[] array1 = {1, 2} and int[] array2 = {1,2}, Java considers them as 2 different arrays. In addition, It doesn't help me in the case of [1,2] and [2,1]

How can I do it?

4

4 回答 4

1

我没有经过测试,但您可以在添加之前对数组进行排序set

int[] array1 = {1, 2};
Arrays.sort(array1);
set.add(array1);
于 2013-05-01T10:44:00.940 回答
0
List<int[]> b = new ArrayList<int[]>(); // Your list here
for (int[] ar : b) {
    Arrays.sort(ar);
}
Set<int[]> a = new HashSet<>(b);
于 2013-05-01T10:59:25.430 回答
0

使用 HashSet,然后将当前列表的所有内容添加到其中。然后使用 .toArray() 方法取回一个列表。

HashSet<Integer> noDuplicates = new HashSet<Integer>();
Integer[] array = { 1, 2, 2, 3, 3, 4, 1};
System.out.println(Arrays.toString(array));
for (Integer i : array)
  noDuplicates.add(i);
array = noDuplicates.toArray(new Integer[] {});
System.out.println(Arrays.toString(array));

如果您必须经常检查两个数组是否相同,那么您可能只想使用 Set 而不是数组,因为它可以节省您将所有内容放入 Set 然后检查的额外步骤。

于 2013-05-01T10:39:06.293 回答
0
  1. 用于Iterator迭代list.
  2. 使用Arrays.equals(arg0, arg1)方法比较里面的数组list
  3. 如果您发现相等的数组,请使用iterator.remove().
于 2013-05-01T10:39:13.507 回答