原始碼中 Comparator.comparing()需要接收一個Function型別的引數:
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));
}
為何在時間使用時,可以傳入Supplier型別的引數呢,如下
Supplier<String> colorStr = apple::getColor;
apples.sort(Comparator.comparing(Apple::getColor));
apple::getColor的回傳值型別明明是Supplier型別的,居然可以出傳入comparing方法中,而 Function和 Supplier 在原始碼中沒有實作和繼承等關系
uj5u.com熱心網友回復:
還有一個 問題Collectors.toList()方法的原始碼:
public static <T>
Collector<T, ?, List<T>> toList() {
return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
(left, right) -> { left.addAll(right); return left; },
CH_ID);
}
new CollectorImpl第二個引數傳入的是 List::add
然而函式定義卻是這樣子的:
CollectorImpl(Supplier<A> supplier,
BiConsumer<A, T> accumulator,
BinaryOperator<A> combiner,
Set<Characteristics> characteristics) {
this(supplier, accumulator, combiner, castingIdentity(), characteristics);
}
BiConsumer<A, T> accumulator,是怎么接收List::add 的呢 ,按理講 List::add是典型的BiPredicate型別啊
uj5u.com熱心網友回復:
我也沒搞懂為什么。在mybatisplus的LambdaQueryWrapper也是這樣。自己試了試就不得行uj5u.com熱心網友回復:
Supplier<String> colorStr = apple::getColor;apples.sort(Comparator.comparing(Apple::getColor));
很明顯傳進去的不是 colorStr Supplier 型別啊
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/107337.html
標籤:Java相關
上一篇:簡答java題目求答,謝謝
