Search code examples
javaarrayscomparatortreesetimplements

Creating Comparator for TreeSet with 2D Arrays - Java


In my Java program, I have a TreeSet with 2D Arrays in it. 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. However, that contains() doesn't seem to work properly sometimes. 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. What should I do?


Solution

  • The ComparatorMatrix doesn't satisfy the definition of Comparator and that's why you are having problems. 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.

    If there is no definition for an ordering then you have to use another HashSet. Then, you only need to implement hashCode and equals; equals is already implemented. You can easily wrap a matrix within an object that caches the hashCode, so you don't have to recalculate it every time.