Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java 8's Comparator.comparing() cast the return value to Serializable?

Tags:

java

casting

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:

  • the & operator in generic type restrictions (and can infer its purpose here),
  • the 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.

like image 926
kevinarpe Avatar asked Jan 06 '17 06:01

kevinarpe


People also ask

Why should Comparator implement serializable?

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.

What features Java 8 has given for Comparator?

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.

How does Comparator compare function work?

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.

What is Comparator comparing in Java?

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):


1 Answers

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.

like image 162
Andreas Avatar answered Sep 23 '22 02:09

Andreas