Joe Joe - 1 month ago 18
Java Question

using of compareTo in java

I was reading about compareTo in java , I have this code :

import java.util.Comparator;

public class Test {

Comparator<String> caseInsensitive= new Comparator<String>() {
@Override
public int compare(String s, String b) {
return s.compareTo(b);
}
};

public static void main(String[] args) {

Test t = new Test();
System.out.println(((Comparator<String>) t).compare("baba","baba"));

}

}


When I run it I get the following error message :

Exception in thread "main" java.lang.ClassCastException: Test cannot be cast to java.util.Comparator
at Test.main(Test.java:15)


How to correct it?

Answer

Your Test class doesn't implement Comparator<String>, so it cannot be cast to this type. It contains a member that implements that interface.

This would work :

System.out.println(t.caseInsensitive.compare("baba","baba"));

Or you can change your Test class to implement Comparator<String> directly :

public class Test implements Comparator<String> {

    @Override
    public int compare(String s, String b) {
        return s.compareTo(b);
    }

    public static void main(String[] args) {   
        Test t = new Test();
        System.out.println(t.compare("baba","baba"));
    }

}