当前位置: 代码迷 >> 综合 >> Comparator 接口中方法里面的 (ComparatorT Serializable) 是什么意思?
  详细解决方案

Comparator 接口中方法里面的 (ComparatorT Serializable) 是什么意思?

热度:80   发布时间:2023-12-01 20:43:43.0

比如 Comparator 接口中 thenComparing() 方法:

/*** Returns a lexicographic-order comparator with another comparator.* If this {@code Comparator} considers two elements equal, i.e.* {@code compare(a, b) == 0}, {@code other} is used to determine the order.** <p>The returned comparator is serializable if the specified comparator* is also serializable.** @apiNote* For example, to sort a collection of {@code String} based on the length* and then case-insensitive natural ordering, the comparator can be* composed using following code,** <pre>{@code*     Comparator<String> cmp = Comparator.comparingInt(String::length)*             .thenComparing(String.CASE_INSENSITIVE_ORDER);* }</pre>** @param  other the other comparator to be used when this comparator*         compares two objects that are equal.* @return a lexicographic-order comparator composed of this and then the*         other comparator* @throws NullPointerException if the argument is null.* @since 1.8*/default Comparator<T> thenComparing(Comparator<? super T> other) {Objects.requireNonNull(other);return (Comparator<T> & Serializable) (c1, c2) -> {int res = compare(c1, c2);return (res != 0) ? res : other.compare(c1, c2);};}

(Comparator & Serializable),& 是 Java8 的新语法,表示同时满足两个约束(约束这个词不知道用的恰不恰当)。相当于:

default Comparator<T> thenComparing(Comparator<? super T> other) {Objects.requireNonNull(other);return (Comparator<T>)(Serializable) (c1, c2) -> {int res = compare(c1, c2);return (res != 0) ? res : other.compare(c1, c2);};}

这意味着结果值将被转换为 Comparator 和 Serializable(即可序列化的比较器)。
请注意,在进行该类转换时,您只能指定一个类(以及无限量的接口),因为 Java 不支持类继承多个类。

  相关解决方案