What is the difference between type T and Object ?
In other words what is the difference between between List<T>
and List<Object>
?
At runtime, there is no difference: Java generics are implemented through Type Erasure, so the same class is used in all implementations.
At compile time, however, the difference is enormous, because it lets you avoid casting every time that you use an object, making you code look a lot cleaner.
Consider this example:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
for (Integer n : list) {
System.out.println(n+5);
}
This compiles and runs well, and it also easy to read. If you wanted to use List<Object>
instead, the code would not look as clean:
List<Object> list = new ArrayList<Object>();
list.add(1);
list.add(2);
list.add(3);
for (Object o : list) {
// Now an explicit cast is required
Integer n = (Integer)o;
System.out.println(n+5);
}
Internally, though, the two code snippets use the same exact implementation for their list
object.
List<T>
is called a generic, and hence guarantees that the List will always contain objects of type T. While the other one doesn't guarantee that the objects are of the same type, in fact you only know that they are objects.
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