为什么如果我在 List 的排序方法中放置一个带有 Comparator 的匿名类,编译器会显示错误?
我的代码:
public class Example2 {
public static void main(String[] args) {
List<String> l = Arrays.asList("a","b","c","d");
l.sort(Comparator<String> c= new Comparator<>() { //compiler error
public int compare(String a, String b) {
return b.compareTo(a);
}
});
}
sort 方法接受一个比较器。如果我编写此代码,它将编译:
public class Example2 {
public static void main(String[] args) {
List<String> l = Arrays.asList("a","b","c","d");
l.sort(new Comparator<String>() { //it's ok
public int compare(String a, String b) {
return b.compareTo(a);
}
});
}
或者这段代码:
public class Example2 {
public static void main(String[] args) {
List<String> l = Arrays.asList("a","b","c","d");
Comparator <String> c = new Comparator<String>() {
public int compare(String a, String b) {
return b.compareTo(a);
}
};
l.sort(c); //it's ok
}
为什么会这样?
非常感谢!
明月笑刀无情
眼眸繁星
莫回无
相关分类