In the book OCP Study Guide there is this example about a Comparator that can be initialized in two ways. The first is via an anonymous class like this:
Comparator<Duck> byWeight = new Comparator<Duck>(){
public int compare(Duck d1, Duck d2){
return d1.getWeight() - d2.getWeight();
}
};
This I can understand. According to the book this can be replaced with a lambda expression like this:
Comparator<Duck> byWeight = (d1,d2) -> d1.getWeight() - d2.getWeight();
Now this I don't understand. The lambda expression does not return a Comparator object, which it couldn't now that I think of it since Comparator is an interface.
So does the new
operator in the first example refer to the anonymous class that is being made which is called Comparator because that anonymous class implements the Comparator interface?
What exactly is happening in example 2 then? Is an object created somehow out of the lambda expression? In this example you use byWeight
as a reference variable right?
I really don't understand this, could anyone please explain? Thank you.