Can someone explain this java generics syntax?

public static <T> List<T> listAndCast(Query query) {
        List<T> list = query.list();
        return list;


On the next line:

public static <T> List<T> listAndCast(Query query) {


Why do we need <T>



source to share

4 answers


tells Java that it is a generic method that defines its own type parameter, instead of relying on one defined for the entire class, like

public class Stuff<T> {}



It doesn't really help.

At the calling site, it allows you to assign a result List

with any type parameter that is not very type safe. All this code is just giving you a false sense of security. If it returns, for example, List<String>

then as written, you will be allowed to assign that result List<Integer>

, and you won't know you squinted until much later (when you try to access the element from List

and assign it Integer

), and the implicit casting will hit face.

In general, if a generic method (such as one that has its own type parameters, separated from the class of which it is a member) only uses its type parameter once and / or only uses it for the return value, it is a complete waste time!



Which tells java that listAndCast is a generic method that depends on the type T.

side note: I prefer this implementation for this problem as it is more general:

public <T> List<T> list_cast(List<?> orig) {
    return (List<T>)orig;




You don't need it <T>

, but it stops compiler warnings. The compiler will infer what is being returned List<Object>

(it has no other information about the type to be returned).

This is essentially the same as:

public static List listAndCast(Query query)


No warnings about raw types.


can be useful if the passed argument has been parameterized with <T>

, for example:

public static <T> List<T> listAndCast(Query<T> query) 




All Articles