Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics: Type Extension In Method Declaration Parameters

I am learning Java Generics. My understanding is that Generics parameterize Collections by type. In the Oracle tutorial there is the following comment:

In generic code, the question mark (?), called the wildcard, represents an unknown type.

On the next page there is the following example of method declaration with an upper-bounded wildcard in the parameters:

public void process(List<? extends Foo> list)

Given that, I am wondering why this method declaration is illegal:

public void process(List<E extends Number> list)

while this one is legal:

public <E extends Number> void process(List<E> list)
like image 293
Schemer Avatar asked Feb 27 '14 20:02

Schemer


People also ask

How do you declare a generic method in Java?

For static generic methods, the type parameter section must appear before the method's return type. The complete syntax for invoking this method would be: Pair<Integer, String> p1 = new Pair<>(1, "apple"); Pair<Integer, String> p2 = new Pair<>(2, "pear"); boolean same = Util. <Integer, String>compare(p1, p2);

How do you declare a generic bounded type parameter in Java?

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number . Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).

What is type parameters in generics?

In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type.


1 Answers

When specifying the method parm types, you're using the generic type, so it has to be defined upfront. In this statement, you use E without definition

public void process(List<E extends Number> list) { /* ... */ }

However, in the second one, it is defined before the method return type (void):

public <E extends Number> void process(List<E> list) { /* ... */ }
like image 178
Ali Cheaito Avatar answered Oct 21 '22 06:10

Ali Cheaito