了解终端操作方法的声明

Understand declaration of a terminal operation method

通常,方法的声明会显示其 return 类型、方法完整路径和参数。但是当我看方法时 java.util.stream.Stream.collect 我很困惑。

似乎该方法有两个 return类型:

<List<Integer>, Object> List<Integer> java.util.stream.Stream.collect(Collector<? super Integer, Object, List<Integer>> collector)

我理解它的realreturn类型是List<Integer>,但是<List<Integer>, Object>是什么意思呢?为什么它在List<Integer>之前是一个space,为什么它的键(如果它是一个映射?)和真正的return类型一样?

看看方法的声明:

public interface Stream<T> extends BaseStream<T, Stream<T>> {
    ...
    /* ...
     * @param <R> the type of the result
     * @param <A> the intermediate accumulation type of the {@code Collector}
     * ...
     */
    <R, A> R collect(Collector<? super T, A, R> collector);
    ...
}

正如 Nathan 在评论中指出的那样,<R, A> 表示泛型类型参数。只要是明确的,Java 编译器就会推断出这些。在您的情况下,R 被推断为 List<Integer>A 被推断为 Object。您可以阅读 here 关于泛型方法的内容。