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

In the following line:

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

Why do we need <T> ?

brainydexter
  • 19,826
  • 28
  • 77
  • 115

4 Answers4

5

The <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, e.g.

public class Stuff<T> {}

Urs Reupke
  • 6,791
  • 3
  • 35
  • 49
2

It doesn't really help at all.

At the call site, it allows you to assign the result to a List with any type parameter, which isn't very type-safe. All this code simply bestows a false sense of security on you. If it returns, for example, a List<String> then as written you will be allowed to assign that result to a List<Integer> and you won't know you've screwed up until much later on (when you try and access an element of the List and assign it to an Integer) and the implicit cast blows up in your face.

Generally, if a generic method (e.g. one which has its own type parameters separate from the class it's a member of) only uses its type parameter once and/or only uses it for the return value, it is a total waste of time!

dty
  • 18,795
  • 6
  • 56
  • 82
  • Unfortunately this is the least painful way of dealing with legacy API that returns plain `List`, but you _know_ that it really returns `List`. – mitchnull Mar 20 '12 at 09:08
  • I agree with @mitchnull. Came across the same thing here: http://stackoverflow.com/questions/115692/how-to-avoid-type-safety-warnings-with-hibernate-hql-results and Thanks for the insight on what's going on here! – brainydexter Mar 20 '12 at 09:15
  • That's probably the only valid use – dty Mar 20 '12 at 09:18
0

That's what tells java that listAndCast is a generic method that depends on the T type.

side note: I prefer this implementation for this problem, as it's more generic:

@SuppressWarnings("unchecked")
public <T> List<T> list_cast(List<?> orig) {
    return (List<T>)orig;
}
mitchnull
  • 6,161
  • 2
  • 31
  • 23
0

You don't need <T>, but it does stop compiler warnings. The compiler will infer that a List<Object> will be returned (it has no other information about the type that will be returned).

It's essentially the same as:

public static List listAndCast(Query query)

Without warnings about raw types.

<T> might be useful if a passed argument was parameterized with <T>, e.g:

public static <T> List<T> listAndCast(Query<T> query) 
Will
  • 877
  • 11
  • 25