What <T>
signifies in following code snippet?
class Test {
<T> void say() {
}
}
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.
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.
See this doc about generics in java
But it is useful only if you have parametized types in the argument list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With