Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Error: Comparator is not abstract and does not override abstract method compare(Object,Object) in Comparator

I have a Sorting.java file, with the following structure:

public class Sorting {
    public static <T> void mergeSort(T[] arr, Comparator<T> comparator) {
    (...)
    }
}

My goal is to test the mergeSort() method in a separate Driver.java file.

To that effect, here is what I included in that driver file:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import java.util.Comparator;
import java.io.*;
import java.util.*;

public class Driver {
    public static void main(String[] args) {
        int[] testMergeSort1 = { 9, 13, 5, 6, 12, 10, 3, 7, 2, 8, 0, 15, 1, 4, 14, 11 };
        mergeSort(testMergeSort1, IntegerComparator);
        System.out.println(Arrays.toString(testMergeSort1));
    }
}

And, per the accepted answer to this similar question, I added the following implementation of an Integer comparator to that same Driver.java file:

public class IntegerComparator implements Comparator {
    public int compare(Integer a, Integer b) {
        return a.intValue() - b.intValue();
    }

    public int equals(Object obj) {
        return this.equals(obj);
    }
}

However, when I compile Driver.java, I get the following error:

Driver.java:33: error: Driver.IntegerComparator is not abstract and does not override abstract method compare(Object,Object) in Comparator
    public class IntegerComparator implements Comparator {
           ^
Driver.java:38: error: equals(Object) in Driver.IntegerComparator cannot implement equals(Object) in Comparator
        public int equals(Object obj) {
                   ^
  return type int is not compatible with boolean

Any guidance on how to proceed to test the mergeSort() method from the Sorting.java file in the separate Driver.java file would be appreciated.

>Solution :

Try to implement a generic Comparator<Integer> and add @Override annotations, to check if you actually override the method in Comparator.

public class IntegerComparator implements Comparator<Integer> {
    @Override
    public int compare(Integer a, Integer b) {
        return a.intValue() - b.intValue();
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading