indeed, I found that passage also confusing. But what I always do when I am unsure of a method reference: I replace that reference by the full lambda version, to see what I end up with.
So, let's take a look at Comparator::naturalOrder (or reversedOrder for that matter): we need a Comparator, a Comparator takes two input parameters and returns an int. So, let us replace it with the full version:
And the book rightfuly remarks that this is incorrect, since the method 'Comparator.naturalOrder()' is a method that takes no parameters! And there you have the compiler error!
But you CAN use a methodreference if you want to. Comparator.naturalOrder() (with one dot!) returns a Comparator, that has the method: compare(a, b). So you can say:
I had to practise this quite a few times before I got the hang of it (and sometimes I still err), but if in doubt, as I said, I try to use the full version.
[Note: this was written without seeing Piet's message. So, I'm replying to the original poster here, not Piet. - Mike]
They aren't quite the same thing.
Comparator.reverseOrder() returns a Comparator - when the code is executed, the Comparator actually exists, and a reference to that comparator is passed to... well, whatever method it's being passed to. (Looks like there's a typo in the code you showed.)
Comparator::reverseOrder gives a reference to a method that could give you a Comparator. If someone were to invoke that method. Which they haven't, yet.
The first method can be used like this:
While the second method requires something more to actually get a Comparator from the reference:
That feels good. Thanks. Here's a tiny ad:
Create Edit Print & Convert PDF Using Free API with Java