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 anyone explain this in this context? Who decides what T is? What is going on here?

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

+5
source share
3 answers

You missed the return type, but beyond that, this is a general method. As with generic types, Tstands for any reference type (within boundaries, if specified).

. , :

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

, , . , <> . .

, , .

, ++ # /.

+11

- , . <T> . Collections ; , .

, T - , . , .

, static <T> Set<T> Collections.singleton(T o) :

Collections.singleton(String T)

a Set<String>.

. , Collection.emptyList(). : Collection.<String>emptyList().

+2

T - , , .

, List Iterator java.util:

public interface List<E>{
  void add(E x);
  Iterator<E> iterator();
}

public interface Iterator<E>{
  E next();
  boolean hasNext();
}

:

List<String> ls = new ArrayList<String>()

, List List, E String:

public interface StringList{
  void add(String x)
  Iterator<String> iterator();
}
0

All Articles