javacomparatoranonymous-inner-class

Use of anonymous class in sort method


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!


Solution

  • The first one fails as it is an assignment. The sort method expects an object of the Comparator class. So when you say sort(new Comparator), you are creating a new Comparator and immediately passing it to the sort method. When you have Comparator c = new Comparator () and then you have sort(c), you create an new Comparator, store it in variable c, and pass it to the sort method.

    The first segment of code tries to both assign a new Comparator to variable c and pass it to method sort, the syntax of java does not allow this. It is analagous to having a method that takes one integer as argument and writing foo(int bar = 7). It doesnt quite make sense.