在java中使用compareTo

时间:2016-10-25 09:55:00

标签: java

我在java中读到有关compareTo的内容,我有这段代码:

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

    }

}

当我运行它时,我收到以下错误消息:

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

如何纠正?

1 个答案:

答案 0 :(得分:3)

您的Test类未实现Comparator<String>,因此无法将其转换为此类型。它包含一个实现该接口的成员。

这样可行:

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

或者您可以更改Test课程以直接实施Comparator<String>

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

}