简体   繁体   中英

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?

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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