Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what <T> signifies in <T> void say() [duplicate]

Tags:

java

generics

What <T> signifies in following code snippet?

class Test {    
     <T> void say() {

     }    
}
like image 613
Dhanashri Avatar asked Jan 10 '13 15:01

Dhanashri


3 Answers

In your example it really does not make sense. But in other cases, if method's return type is void <T> still can be used as expected generic parameters type. Consider this

public static <T> void test(List<T> list1, List<T> list2) {
    list1.addAll(list2);
}

public static void main(String[] args) throws Exception {
    test(Arrays.asList(1, 1), Arrays.asList("1", "1"));
}

type safety control, javac gives an error, test() expects Lists of the same type.

Another example java.util.Collections.fill

public static <T> void fill(List<? super T> list, T obj) {
    ....
}    

type safety control again.

like image 128
Evgeniy Dorofeev Avatar answered Sep 26 '22 02:09

Evgeniy Dorofeev


It introduces a type placeholder, where T maybe pretty much any type. This is typically useful if T is part of the signature (either as a parameter or a return type):

<T> void say(T myT) {}
say<Object>(myObject);
say<String>(myString);

<U> U foo(U u) { return u; }
String s = foo<String>("");

It's rarely useful to introduce a type parameter just for internal use, as the actual T is often more interesting for the consumer than the method.

like image 29
Matthias Meid Avatar answered Sep 22 '22 02:09

Matthias Meid


See this doc about generics in java

But it is useful only if you have parametized types in the argument list.

like image 24
autra Avatar answered Sep 25 '22 02:09

autra