0

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?

Joe
  • 65
  • 1
  • 6
  • Note that casts, whilst *occasionally* necessary, are a bit of a code smell. If you inserted the cast because it said the symbol `t.compare` could not be found, that's because, well, it could not be found. You should understand the error messages first, before trying to work around them. – Andy Turner Oct 25 '16 at 10:01
  • "I was reading about compareTo in java" you know you don't actually use `compareTo` in this code? :) – Andy Turner Oct 25 '16 at 10:05

1 Answers1

3

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"));
    }

}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • will work, but wont do what it's name says... `compare` method return must be `return s.compareToIgnoreCase(b);` or `return s.toLowerCase().compareTo(b.toLowerCase());` to be consistent – Jordi Castilla Oct 25 '16 at 10:01
  • 1
    @JordiCastilla That's true – Eran Oct 25 '16 at 10:03
  • does that mean that when I have such method :` public int compare(String s, String b) {` then I have to implement `Comparator` ? – Joe Oct 25 '16 at 10:08
  • @Joe It's not enough to implement the method if you want to cast to the type of the interface. You have to declare that the class implements the interface. However, in the snippet I added to my answer, your `Test` class doesn't have to implement `Comparator`, since I don't cast `t` to `Comparator`. – Eran Oct 25 '16 at 10:12