简体   繁体   English

java 泛型方法签名

[英]java generic method signature

I'm a bit confused about the syntax of generic methods.我对泛型方法的语法有点困惑。 My understanding after reading this post was that generic method should be declared like this:读完这篇文章后我的理解是泛型方法应该这样声明:

public static <E> void printArray( E[] inputArray )

with <E> being a placeholder that informs that E is a generic type <E>是一个占位符,通知 E 是泛型类型

So why do I find in the javadoc things like this:那么为什么我会在javadoc中找到这样的内容:

Stream<T> filter(Predicate<? super T> predicate)

No placeholder?没有占位符? I would have expect我本来期望

<T> Stream<T> filter(Predicate<? super T> predicate)

And why以及为什么

<R> Stream<R> map(Function<? super T,? extends R> mapper)

This time there is a placeholder, but only for R and not for T. Why?这次有一个占位符,但只针对 R 而不是针对 T。为什么?

These methods are instance methods defined on the interface Stream , which defines the type parameter on the type :这些方法是定义在接口Stream上的实例方法,它定义了 type 上的type参数:

public interface Stream<T> {
  Stream<T> filter(Predicate<? super T>)
}

...so the type parameter is defined on the interface, not the method. ...所以类型参数是在接口上定义的,而不是在方法上。

As you noticed, type parameters that aren't defined on the interface are defined on a method-by-method basis, in the case of map .正如您所注意到的,在map的情况下,未在接口上定义的类型参数是按方法定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM