1. 程式人生 > >Comparator 介面中方法裡面的 (Comparator & Serializable) 是什麼意思?

Comparator 介面中方法裡面的 (Comparator & Serializable) 是什麼意思?

比如 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 不支援類繼承多個類。