Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between type T and Object? [duplicate]

Tags:

java

generics

What is the difference between type T and Object ?

In other words what is the difference between between List<T> and List<Object>?

like image 819
blue-sky Avatar asked Dec 15 '22 07:12

blue-sky


2 Answers

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.

like image 179
Sergey Kalinichenko Avatar answered Mar 08 '23 03:03

Sergey Kalinichenko


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.

like image 33
Levente Kurusa Avatar answered Mar 08 '23 04:03

Levente Kurusa