list...">

Can someone explain this java generics syntax?

public static <T> List<T> listAndCast(Query query) {
        @SuppressWarnings("unchecked")
        List<T> list = query.list();
        return list;
    }

      

On the next line:

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

      

Why do we need <T>

?

+3


source to share


4 answers


<T>

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> {}

+6


source


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!

+2


source


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:

@SuppressWarnings("unchecked")
public <T> List<T> list_cast(List<?> orig) {
    return (List<T>)orig;
}

      

0


source


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.

<T>

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

, for example:

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

      

0


source







All Articles