Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java generic method signature

Tags:

java

generics

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

So why do I find in the javadoc things like this:

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?

like image 774
Julien Berthoud Avatar asked Sep 11 '25 15:09

Julien Berthoud


1 Answers

These methods are instance methods defined on the interface Stream, which defines the type parameter on the 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.

like image 84
Louis Wasserman Avatar answered Sep 13 '25 06:09

Louis Wasserman