Use of anonymous class in sort method











up vote
1
down vote

favorite












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!










share|improve this question


























    up vote
    1
    down vote

    favorite












    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!










    share|improve this question
























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      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!










      share|improve this question













      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!







      java comparator anonymous-inner-class






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 10 at 17:49









      Adryr83

      869




      869
























          3 Answers
          3






          active

          oldest

          votes

















          up vote
          2
          down vote



          accepted










          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.






          share|improve this answer





















          • It wouldn't matter if it were an assignment; it's not, though, it is a variable declaration, which is a statement, not an expression, and thus cannot be used inside an expression.
            – Andy Turner
            Nov 10 at 20:55


















          up vote
          2
          down vote













          In the second example you are not giving the comparator to the method, you are assigning it to the 'c' reference. In the third example you are assigning it to c reference but then giving it to the sort method.



          Hope this helps :)






          share|improve this answer





















          • Thanks a lot for your answer, but in my opinion, in all examples I assigned a Comparator to sort method, that the sort method accepts.
            – Adryr83
            Nov 10 at 17:58






          • 2




            In l.sort(Comparator<String> c= new Comparator<>() you are giving the sort method the return of the expression Comparator<String> c= new Comparator<>() which is not a Comparator.
            – Andrei Dumitrescu-Tudor
            Nov 10 at 18:01




















          up vote
          2
          down vote













          The problem here is not that you are passing an anonymous class.



          l.sort(Comparator<String> c= new Comparator<>() { ... });


          This is attempting to declare a variable, c. Variable declarations are statements, and so they cannot be used inside expressions. (You also can't use the diamond operator when declaring an anonymous class).



          If you want to declare a variable to hold that comparator, and assign it inside the sort invocation, you can, like so:



          Comparator<String> c;
          l.sort(c = new Comparator<String>() { ... });


          but I suspect that isn't what you intended.






          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53241785%2fuse-of-anonymous-class-in-sort-method%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            2
            down vote



            accepted










            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.






            share|improve this answer





















            • It wouldn't matter if it were an assignment; it's not, though, it is a variable declaration, which is a statement, not an expression, and thus cannot be used inside an expression.
              – Andy Turner
              Nov 10 at 20:55















            up vote
            2
            down vote



            accepted










            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.






            share|improve this answer





















            • It wouldn't matter if it were an assignment; it's not, though, it is a variable declaration, which is a statement, not an expression, and thus cannot be used inside an expression.
              – Andy Turner
              Nov 10 at 20:55













            up vote
            2
            down vote



            accepted







            up vote
            2
            down vote



            accepted






            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.






            share|improve this answer












            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.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 10 at 17:58









            Jacob

            24519




            24519












            • It wouldn't matter if it were an assignment; it's not, though, it is a variable declaration, which is a statement, not an expression, and thus cannot be used inside an expression.
              – Andy Turner
              Nov 10 at 20:55


















            • It wouldn't matter if it were an assignment; it's not, though, it is a variable declaration, which is a statement, not an expression, and thus cannot be used inside an expression.
              – Andy Turner
              Nov 10 at 20:55
















            It wouldn't matter if it were an assignment; it's not, though, it is a variable declaration, which is a statement, not an expression, and thus cannot be used inside an expression.
            – Andy Turner
            Nov 10 at 20:55




            It wouldn't matter if it were an assignment; it's not, though, it is a variable declaration, which is a statement, not an expression, and thus cannot be used inside an expression.
            – Andy Turner
            Nov 10 at 20:55












            up vote
            2
            down vote













            In the second example you are not giving the comparator to the method, you are assigning it to the 'c' reference. In the third example you are assigning it to c reference but then giving it to the sort method.



            Hope this helps :)






            share|improve this answer





















            • Thanks a lot for your answer, but in my opinion, in all examples I assigned a Comparator to sort method, that the sort method accepts.
              – Adryr83
              Nov 10 at 17:58






            • 2




              In l.sort(Comparator<String> c= new Comparator<>() you are giving the sort method the return of the expression Comparator<String> c= new Comparator<>() which is not a Comparator.
              – Andrei Dumitrescu-Tudor
              Nov 10 at 18:01

















            up vote
            2
            down vote













            In the second example you are not giving the comparator to the method, you are assigning it to the 'c' reference. In the third example you are assigning it to c reference but then giving it to the sort method.



            Hope this helps :)






            share|improve this answer





















            • Thanks a lot for your answer, but in my opinion, in all examples I assigned a Comparator to sort method, that the sort method accepts.
              – Adryr83
              Nov 10 at 17:58






            • 2




              In l.sort(Comparator<String> c= new Comparator<>() you are giving the sort method the return of the expression Comparator<String> c= new Comparator<>() which is not a Comparator.
              – Andrei Dumitrescu-Tudor
              Nov 10 at 18:01















            up vote
            2
            down vote










            up vote
            2
            down vote









            In the second example you are not giving the comparator to the method, you are assigning it to the 'c' reference. In the third example you are assigning it to c reference but then giving it to the sort method.



            Hope this helps :)






            share|improve this answer












            In the second example you are not giving the comparator to the method, you are assigning it to the 'c' reference. In the third example you are assigning it to c reference but then giving it to the sort method.



            Hope this helps :)







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 10 at 17:55









            Andrei Dumitrescu-Tudor

            875




            875












            • Thanks a lot for your answer, but in my opinion, in all examples I assigned a Comparator to sort method, that the sort method accepts.
              – Adryr83
              Nov 10 at 17:58






            • 2




              In l.sort(Comparator<String> c= new Comparator<>() you are giving the sort method the return of the expression Comparator<String> c= new Comparator<>() which is not a Comparator.
              – Andrei Dumitrescu-Tudor
              Nov 10 at 18:01




















            • Thanks a lot for your answer, but in my opinion, in all examples I assigned a Comparator to sort method, that the sort method accepts.
              – Adryr83
              Nov 10 at 17:58






            • 2




              In l.sort(Comparator<String> c= new Comparator<>() you are giving the sort method the return of the expression Comparator<String> c= new Comparator<>() which is not a Comparator.
              – Andrei Dumitrescu-Tudor
              Nov 10 at 18:01


















            Thanks a lot for your answer, but in my opinion, in all examples I assigned a Comparator to sort method, that the sort method accepts.
            – Adryr83
            Nov 10 at 17:58




            Thanks a lot for your answer, but in my opinion, in all examples I assigned a Comparator to sort method, that the sort method accepts.
            – Adryr83
            Nov 10 at 17:58




            2




            2




            In l.sort(Comparator<String> c= new Comparator<>() you are giving the sort method the return of the expression Comparator<String> c= new Comparator<>() which is not a Comparator.
            – Andrei Dumitrescu-Tudor
            Nov 10 at 18:01






            In l.sort(Comparator<String> c= new Comparator<>() you are giving the sort method the return of the expression Comparator<String> c= new Comparator<>() which is not a Comparator.
            – Andrei Dumitrescu-Tudor
            Nov 10 at 18:01












            up vote
            2
            down vote













            The problem here is not that you are passing an anonymous class.



            l.sort(Comparator<String> c= new Comparator<>() { ... });


            This is attempting to declare a variable, c. Variable declarations are statements, and so they cannot be used inside expressions. (You also can't use the diamond operator when declaring an anonymous class).



            If you want to declare a variable to hold that comparator, and assign it inside the sort invocation, you can, like so:



            Comparator<String> c;
            l.sort(c = new Comparator<String>() { ... });


            but I suspect that isn't what you intended.






            share|improve this answer

























              up vote
              2
              down vote













              The problem here is not that you are passing an anonymous class.



              l.sort(Comparator<String> c= new Comparator<>() { ... });


              This is attempting to declare a variable, c. Variable declarations are statements, and so they cannot be used inside expressions. (You also can't use the diamond operator when declaring an anonymous class).



              If you want to declare a variable to hold that comparator, and assign it inside the sort invocation, you can, like so:



              Comparator<String> c;
              l.sort(c = new Comparator<String>() { ... });


              but I suspect that isn't what you intended.






              share|improve this answer























                up vote
                2
                down vote










                up vote
                2
                down vote









                The problem here is not that you are passing an anonymous class.



                l.sort(Comparator<String> c= new Comparator<>() { ... });


                This is attempting to declare a variable, c. Variable declarations are statements, and so they cannot be used inside expressions. (You also can't use the diamond operator when declaring an anonymous class).



                If you want to declare a variable to hold that comparator, and assign it inside the sort invocation, you can, like so:



                Comparator<String> c;
                l.sort(c = new Comparator<String>() { ... });


                but I suspect that isn't what you intended.






                share|improve this answer












                The problem here is not that you are passing an anonymous class.



                l.sort(Comparator<String> c= new Comparator<>() { ... });


                This is attempting to declare a variable, c. Variable declarations are statements, and so they cannot be used inside expressions. (You also can't use the diamond operator when declaring an anonymous class).



                If you want to declare a variable to hold that comparator, and assign it inside the sort invocation, you can, like so:



                Comparator<String> c;
                l.sort(c = new Comparator<String>() { ... });


                but I suspect that isn't what you intended.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 10 at 21:00









                Andy Turner

                78k877128




                78k877128






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53241785%2fuse-of-anonymous-class-in-sort-method%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Florida Star v. B. J. F.

                    Error while running script in elastic search , gateway timeout

                    Adding quotations to stringified JSON object values