Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic method declaration [duplicate]

Tags:

java

generics

I'm learning Java generics and I ask myself this question.

What is the difference between these two method declarations?

public static void someMethod(List<? extends Number> numberList); 

and

public static <E extends Number> void someMethod(List<E> numberList); 
like image 950
ZeDonDino Avatar asked Feb 20 '13 11:02

ZeDonDino


People also ask

Can a generic class have multiple generic parameters Java?

A Generic class can have muliple type parameters.

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);

Do generics allow for code reuse?

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.

Can generic methods be overloaded?

A generic method can also be overloaded by nongeneric methods. When the compiler encounters a method call, it searches for the method declaration that best matches the method name and the argument types specified in the call—an error occurs if two or more overloaded methods both could be considered best ...


1 Answers

In the latter you have a reference to the type within the scope of someMethod, namely E. In the former you do not.

like image 172
Rich O'Kelly Avatar answered Sep 21 '22 17:09

Rich O'Kelly