Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : What is - public static<T> foo() {...}?

I saw a java function that looked something like this-

public static<T> foo() {...}

I know what generics are but can someone explain the in this context? Who decides what T is equal to? Whats going on here?

EDIT: Can someone please show me an example of a function like this.

like image 631
quilby Avatar asked Jul 07 '09 15:07

quilby


2 Answers

You've missed the return type out, but apart from that it's a generic method. As with generic types, T stands in for any reference type (within bounds if given).

For methods, generic parameters are typically inferred by the compiler. In certain situations you might want to specify the generic arguments yourself, using a slightly peculiar syntax:

    List<String> strings = Collections.<String>emptyList();

In this case, the compiler could have inferred the type, but it's not always obvious whether the compiler can or can't. Note, the <> is after the dot. For syntactical reasons the type name or target object must always be specified.

It's possible to have generic constructors, but I've never seen one in the wild and the syntax gets worse.

I believe C++ and C# syntaxes place the generic types after the method/function name.

like image 141
Tom Hawtin - tackline Avatar answered Oct 04 '22 12:10

Tom Hawtin - tackline


The context is a generic method as opposed to a class. The variable <T> applies only to the call of the method.. The Collections class has a number of these; the class itself is not generic, but many of the methods are.

The compiler decides what T is equal to -- it equals whatever gets the types to work. Sometimes this is easier then others.

For example, the method static <T> Set<T> Collections.singleton(T o) the type is defined in the parameter:

Collections.singleton(String T)

will return a Set<String>.

Sometimes the type is hard to define. For example sometimes there is not easily enough information to type Collection.emptyList(). In that case you can specify the type directly: Collection.<String>emptyList().

like image 28
Kathy Van Stone Avatar answered Oct 04 '22 13:10

Kathy Van Stone