【问题标题】:Understand declaration of a terminal operation method [duplicate]了解终端操作方法的声明[重复]
【发布时间】:2017-09-12 02:06:24
【问题描述】:

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

该方法似乎有两种返回类型:

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

我知道它的real返回类型是List&lt;Integer&gt;,但是&lt;List&lt;Integer&gt;, Object&gt;是什么意思呢?为什么List&lt;Integer&gt;前面有一个空格,为什么它的key(如果是map?)和真正的返回类型一样?

【问题讨论】:

  • 第一件事不是返回类型,它指定了泛型类型参数 R 和 A 的类型。阅读 javadoc 在这里会有所帮助。方法返回R,所以返回类型必须和类型参数一致

标签: methods declaration return-type collectors


【解决方案1】:

看一下方法的声明:

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 在 cmets 中指出的,&lt;R, A&gt; 表示泛型类型参数。只要它们是明确的,这些将由 Java 编译器推断。在您的情况下,R 被推断为List&lt;Integer&gt;A 被推断为Object。你可以阅读here 了解泛型方法。

猜你喜欢
  • 2015-02-23
  • 1970-01-01
  • 1970-01-01
  • 2020-03-05
  • 1970-01-01
  • 2012-03-05
  • 2012-10-15
  • 1970-01-01
相关资源
最近更新 更多