Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why i need Class Generics?

 
sriram sundararajan
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I understand the need of Generics in Collections. We can avoid runtime error and in the compilation time itself we can identify the exceptions and resolve it.

My doubt is why i need class level Generics? Look at the following code snippet, and advice me what kind of benefit i am getting from making the class b as generics.


 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't. Adding generics should add benefits like no longer having to make casts, or having the risk of ClassCastExceptions.
 
sriram sundararajan
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, i got it. But in the above example, how it make sense?
 
Paul Clapham
Sheriff
Pie
Posts: 20966
31
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sriram sundararajan wrote:But in the above example, how it make sense?

It doesn't. If the person who gave you the code claims that the use of generics provides some benefit, you should ask them why they think that.
 
sriram sundararajan
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am learning generics, i only wrote this code for my understanding.
 
Mike Simmons
Ranch Hand
Posts: 3040
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A generic class can provide benefits, sure. If there's some larger purpose being served. But if you just throw generics into a class, without any planned purpose, it's unlikely you will be able to do anything useful with them. Much like you can't create a sentence in English by simply choosing random words from an English dictionary.

If you want to see what benefits a generic class can provide, I suggest looking at List, and/or ArrayList. If someone gives me a List, how do I know what's in it? Should I just assume that the things inside are, let's say, Strings? Then cast to String and see if we get an exception. Or maybe check first using "if (element instanceof String)". Blech. Much better to get a List<String> in the first place, so you know that the things in the list are Strings. And the compiler knows. And we don't have to guess.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic