4

What is the difference between type T and Object ?

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

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
blue-sky
  • 51,962
  • 152
  • 427
  • 752

3 Answers3

10

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

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.

Levente Kurusa
  • 1,858
  • 14
  • 18
0

List<T> is a name of a generic class. List<Object> is its concrete instantiation. List<T> is not a class yet (it's a generic class, a template you can create concrete classes from but not a class you can use right away), List<Object> is a class.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130