为什么Java 8的Comparator.comparing()将返回值转换为Serializable? [英] Why does Java 8's Comparator.comparing() cast the return value to Serializable?
问题描述
来自JDK8的比较器。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));
}
请注意,return语句的前缀为有趣的强制类型转换:(比较器& T&可序列化)
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?
我不明白意图。
后续处理重复/关闭请求:此问题如何序列化lambda?不回答问题。我的问题特别指出,返回类型没有提及 Serializable
,因此引起了我的困惑。
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.
推荐答案
如果指定的函数也可序列化,则返回的比较器可序列化。
The returned comparator is serializable if the specified function is also serializable.
强制类型转换可确保内部类使用实施lambda的Java将实现可序列化
。
The cast ensures that the internal class used by Java to implement the lambda will implements Serializable
.
这篇关于为什么Java 8的Comparator.comparing()将返回值转换为Serializable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!