简体   繁体   English

使用2D数组为TreeSet创建比较器-Java

[英]Creating Comparator for TreeSet with 2D Arrays - Java

In my Java program, I have a TreeSet with 2D Arrays in it. 在我的Java程序中,我有一个带有2D数组的TreeSet。 However, I don't want any duplicates in it, so I decided to create a class that implements Comparator in order to use the TreeSet's contains() method, to see if I'm adding a duplicate or not. 但是,我不希望有任何重复项,所以我决定创建一个实现Comparator的类,以便使用TreeSet的contains()方法来查看是否添加了重复项。 However, that contains() doesn't seem to work properly sometimes. 但是,有时候contains()似乎无法正常工作。 Here's the Comparator: 这是比较器:

public class ComparatorMatrix implements Comparator<int[][]> {

public int compare(int[][] matrix1, int[][] matrix2) {
    if(Arrays.deepEquals(matrix1, matrix2)) {return 0;}

    return -1;
}

I didn't implement an equals() method, and I have no idea how to do it. 我没有实现equals()方法,也不知道该怎么做。 What should I do? 我该怎么办?

The ComparatorMatrix doesn't satisfy the definition of Comparator and that's why you are having problems. ComparatorMatrix不满足Comparator的定义,这就是您遇到问题的原因。 As Carl Manaster said, you need to properly return if compare(a,b) returns -1 compare(b,a) must return 1 or it won't work within a TreeSet. 正如Carl Manaster所说,如果compare(a,b)返回-1,则需要正确地返回compare(b,a)必须返回1,否则它将在TreeSet中不起作用。

If there is no definition for an ordering then you have to use another HashSet. 如果没有订单的定义,则必须使用另一个HashSet。 Then, you only need to implement hashCode and equals; 然后,您只需要实现hashCode和equals;即可。 equals is already implemented. equals已经实现。 You can easily wrap a matrix within an object that caches the hashCode, so you don't have to recalculate it every time. 您可以轻松地在缓存hashCode的对象中包装矩阵,因此不必每次都重新计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM