Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring generic methods, clarification needed

Tags:

java

generics

Consider the following 2 method declarations:

1. public abstract <T extends MetaData> List<T> execute();
2. public abstract List<? extends MetaData>  execute();

Both seem to return back a list of objects that extend MetaData.

What is the difference between them please?

like image 911
James Raitsev Avatar asked Aug 02 '12 13:08

James Raitsev


People also ask

How do you declare a generic method?

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 type in a class explain?

If we want the data to be of int type, the T can be replaced with Integer, and similarly for String, Character, Float, or any user-defined type. The declaration of a generic class is almost the same as that of a non-generic class except the class name is followed by a type parameter section.

Why do we need generic methods?

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.

What is a generic method and when should it be used?

Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used. It is possible to use both generic methods and wildcards in tandem.


1 Answers

In the first case you will allow Java to use type inference and infer the type of T at each call site.

In the second case you will always get a List<? extends MetaData> and so won't be able to assign it to a variable of any narrower type like List<IntegerMetaData>.

like image 135
Marko Topolnik Avatar answered Oct 06 '22 21:10

Marko Topolnik