您可以创建一个类来表示您的集合元素并为它们提供您想要的行为。也就是说,如果两个元素包含相同的整数而不考虑顺序,则它们相等。
import java.util.Arrays;
public class IntList extends Object {
// I will keep the original array but you can just sort it in place if that makes sense
private int[] array; // The orignal array
private int[] sortedArray; // Sorted copy of the original array
public IntList( int[] array ) {
this.array = array;
this.sortedArray = array.clone();
Arrays.sort( this.sortedArray );
}
@Override
public boolean equals( Object o ) {
// This object is equal to another if they are:
// the same instance or instances of this class with equal sorted arrays
boolean result;
if ( o == this ) {
result = true;
} else {
if ( ! ( o instanceof IntList ) ) {
result = false;
} else {
IntList other = ( IntList ) o;
result = Arrays.equals( this.sortedArray, other.sortedArray );
}
}
return result;
}
@Override
public int hashCode() {
// Used by HashSet
return Arrays.hashCode( this.sortedArray );
}
@Override
public String toString() {
return Arrays.toString( this.sortedArray );
}
}
然后你可以用这个类的元素构造一个Set:
import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;
public class main {
public static void main(String[] args) {
int[][] input = new int[][] { { -1, -1, 2 }, { 0, -1, 1 }, { 1, -1, 0 }, { 2, -1, -1 },
{ -1, 2, -1 }, { -1, 1, 0 }, { 0, 1, -1 }, { -1, 0, 1 }, { 1, 0, -1 } };
System.out.printf("input = %s%n", Arrays.deepToString(input));
Set<IntList> set = new HashSet<IntList>();
for( int[] currIntArray: input ) {
IntList list = new IntList( currIntArray );
set.add( list );
}
System.out.printf( "output = %s%n", set.toString());
}
}
结果
input = [[-1, -1, 2], [0, -1, 1], [1, -1, 0], [2, -1, -1], [-1, 2, -1], [-1, 1, 0], [0, 1, -1], [-1, 0, 1], [1, 0, -1]]
output = [[-1, -1, 2], [0, -1, 1]]
您执行此操作的方式实际上取决于您的问题域的更大背景。我认为您不太可能真的想要一个名为 IntList 的公共类,但您可能会将其包含在您自己的 Set 实现中,或模型中的其他位置。