Hey-men-whatsup Hey-men-whatsup - 2 months ago 21
Java Question

T is parameter type or class type?

I'm really sorry as I thought that I understand generic but I don't, shame on me.

What's the difference between these two

public static <T> void c(T obj) {
System.out.println(obj.toString());
}


and

public static <T> void d(List<T> obj) {
System.out.println(obj.toString());
}


As

List <Integer> l1 = Arrays.asList(new Integer[]{1,2,3});
Gen.c( l1);
Gen.d( l1);


Return the same output
[1, 2, 3]

As
List<T>
obj behaves the same with
T
obj.

T indicates parameter type or type of class/object ?

Answer

In the case of c, your T can be anything, which includes a list. But because Java doesn't know what it is, you can't do any list-specific operations on it.

In the case of d, your T has to be a list. Because Java knows what it is, you can do things like adding and removing and iterating and so on.

Comments