【问题标题】:Why in Collectors.java Class it is possible to use array indexing?为什么在 Collectors.java 类中可以使用数组索引?
【发布时间】:2023-01-08 21:19:02
【问题描述】:

在 collectors.java 类中,我找到了这个方法。我无法解释为什么你可以在这里使用数组索引。我的意思是这条线(a, t) -> { a[0] = op.apply(a[0], mapper.apply(t)); },

public static <T, U> Collector<T, ?, U> reducing(U identity,
                                Function<? super T, ? extends U> mapper,
                                BinaryOperator<U> op) {
        return new CollectorImpl<>(
                boxSupplier(identity),
                (a, t) -> { a[0] = op.apply(a[0], mapper.apply(t)); },
                (a, b) -> { a[0] = op.apply(a[0], b[0]); return a; },
                a -> a[0], CH_NOID);
    }

【问题讨论】:

  • “为什么”是什么意思?因为a 是一个数组?
  • 但是在这个类中的什么地方提到了 a 是一个数组。 CollectorImpl 的第二个参数是 BiConsumer<A, T> 累加器,为了在某处写 a[0] 需要说 a 是一个数组
  • 那么你需要找到正在调用的 CollectorImpl 的构造函数。它可能需要一些功能接口,并且这些功能接口有一个抽象方法,该方法将一些数组作为其第一个参数。
  • 仔细看boxSupplier的签名:)
  • 该过程称为类型推断.

标签: java jvm


【解决方案1】:

为什么这里可以使用数组下标呢?因为它是一个数组,为什么不能像使用其他数组一样使用它呢?

Collectors#reducing 方法返回一个新的 Collector 实例:

    return new CollectorImpl<>(
            boxSupplier(identity),
            (a, t) -> { a[0] = op.apply(a[0], mapper.apply(t)); },
            (a, b) -> { a[0] = op.apply(a[0], b[0]); return a; },
            a -> a[0],
            CH_NOID);

这个CollectorImpl构造函数的签名是:

    CollectorImpl(Supplier<A> supplier,
                  BiConsumer<A, T> accumulator,
                  BinaryOperator<A> combiner,
                  Function<A,R> finisher,
                  Set<Characteristics> characteristics) {

boxSupplier的签名是:

private static <T> Supplier<T[]> boxSupplier(T identity) {
    return () -> (T[]) new Object[] { identity };
}

它返回一个提供数组的 Supplier(有效地将指定的 identity 对象惰性地包装在具有单个元素的数组中)。因此,CollectorImpl 的类型参数 A 是标识类型的数组,这意味着第二个和第三个参数是数组的 BiConsumer 和数组上的 BinaryOperator。因此,lambda 参数列表中的形式参数a 是数组类型。因为它是一个数组,所以它可以像任何其他数组一样使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 2022-12-03
    • 2017-05-22
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多