From JDK8's Comparator.java:
public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
Function<? super T, ? extends U> keyExtractor)
{
Objects.requireNonNull(keyExtractor);
return (Comparator<T> & Serializable)
(c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}
Notice the return statement is prefixed with an interesting cast: (Comparator<T> & Serializable)
I am already aware of and (I think) understand:
&
operator in generic type restrictions (and can infer its purpose here),Serializable
interface.However, used together in the cast is baffling to me.
What is the purpose of & Serializable
if the return type does not require it?
I do not understand the intent.
Follow-up to dupe/close requests: This question How to serialize a lambda? does not answer question. My question specifically notes the return type has no mention of Serializable
, thus the source of my confusion.
Collections like TreeMap have a Comparator object in them, so to be able to produce a byte array that captures every aspect of such collections, you need to be able to save the Comparator as a byte array too. Hence, Comparator needs to be Serializable so that other things can be properly serialized.
Comparator has undergone a major overhaul in Java 8 while still retaining its essence which is to compare and sort objects in Collections. Comparator now supports declarations via lambda expressionsRead Lambda Expressions Tutorial as it is a Functional Interface.
comparing. Accepts a function that extracts a sort key from a type T , and returns a Comparator<T> that compares by that sort key using the specified Comparator . The returned comparator is serializable if the specified function and comparator are both serializable.
A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class. Following function compare obj1 with obj2. Syntax: public int compare(Object obj1, Object obj2):
The javadoc of Comparator.comparing()
says:
The returned comparator is serializable if the specified function is also serializable.
The cast ensures that the internal class used by Java to implement the lambda will implements Serializable
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With