-3

We have generics in java using which we can generalize a class. I know that Object class is the parent class of every class.

When I can typecast to and from Object then why generics are needed?

class Response<T>{
    T data;
}
class Response{
    Object data;
}

Both of the above code snippets will work the same way.

Nakul Kumar
  • 325
  • 1
  • 5
  • 11
  • 4
    Type safety. And you no longer have to cast. – Slaw May 31 '19 at 15:47
  • I'd read [this](https://stackoverflow.com/questions/44841156/java-generics-type-safety) – GBlodgett May 31 '19 at 15:48
  • Also related, "why use Java (x >=5) when you can stay with Java 4?" Jokes aside, start [here](https://en.wikipedia.org/wiki/Generics_in_Java). – Mena May 31 '19 at 15:49
  • Generics allow you to find issues during compilation and not by observing `ClassCastException` during runtime – Ivan May 31 '19 at 16:10

3 Answers3

4

That's how things were done before generics existed: you declared objects of type Object when you didn't know their specific type.

But an Object type doesn't say much, the benefit of generics is that now we know what's the type of the object, as far as it's possible at compile time. Read about type erasure to understand the limitations of the way Generics were implemented in Java.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
3

I can make a list in the "pre-generic" way and do something terrible like this. The result is I can't know the type of the object I get from the list without resorting to reflection.

List myList = new ArrayList();
myList.add(new Integer(1));
myList.add(new Cat());

Object whatIsThis = myList.get(1);

With generics, I can say

List<Cat> myList = new ArrayList();    
myList.add(new Cat());
myList.add(new Integer(1));  // compile time error
myList.add(new Dog()); // compile time error

Cat whatIsThis = myList.get(1); // I *know* this must be a Cat
munk
  • 12,340
  • 8
  • 51
  • 71
0

Casting(Boxing and Unboxing) is an expensive run-time operation. Generics incur no run-time overhead.

  • This answer is incorrect. Boxing and unboxing still happens at run-time. And generics still require a cast at runtime, it's only that you don't have to write it explicitly. – Óscar López May 31 '19 at 15:52
  • @ÓscarLópez, I have "corrected" the answer. From your link: "The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods." The point of the answer was performance and type safety is better with generics. The compiler will resort to `Object` only when the " if the type parameters are unbounded", and thus require casts. –  May 31 '19 at 16:13