Java generics T vs Object

Isolated from context – no difference. On both t and obj you can invoke only the methods of Object.

But with context – if you have a generic class:

MyClass<Foo> my = new MyClass<Foo>();
Foo foo = new Foo();

Then:

Foo newFoo = my.doSomething(foo);

Same code with object

Foo newFoo = (Foo) my.doSomething(foo);

Two advantages:

  • no need of casting (the compiler hides this from you)
  • compile time safety that works. If the Object version is used, you won’t be sure that the method always returns Foo. If it returns Bar, you’ll have a ClassCastException, at runtime.

Leave a Comment