Jordi
Jordi

Reputation: 23247

Java: Generic method or generic class

I've seen this signature exploring a library implementation:

public final class QueryResults<T> {
    public static <T> QueryResults<T> emptyResults() {
        return (QueryResults<T>) EMPTY;
    };
}

I don't quite figure out:

  1. Why T is declared again into function signature, when T is already declared into class definition?
  2. Why method return an <T> instead of a T?

Upvotes: 2

Views: 135

Answers (2)

michid
michid

Reputation: 10814

These T have different scopes. The one in the class declaration extends over instances of the class. The one in the static method only extends over the method signature and body. You could use different names for these type variables to avoid confusion.

Regarding the second part of the question: the method does not return a <T>. It returns a QueryResults<T>. The former is rather a declaration of the the type variable <T>.

Upvotes: 0

SLaks
SLaks

Reputation: 887449

Due to Type Erasure, generics only apply at compile time to an instance of a class. QueryResults<...> is not valid as a static identifier.

Therefore, to make a static method that uses a type parameter, you must declare the type parameter on the method, creating a generic method.

<T> is the declaration of the type parameter, not the return type (the return type is QueryResults<T>).

Upvotes: 3

Related Questions