why if I put an anonymous class with Comparator in the sort method of List the compiler show me an error?
My code:
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);
}
});
}
The sort method accepts a Comparator. If I write this code, it compiles:
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);
}
});
}
Or this code:
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
}
Why does it happen?
Thanks a lot!