Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

don't see how generic class is useful in common cases

 
Raj Ohadi
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know genric class can take different types. But for some daily projects, I still don't see this feature is quite useful. For example, if I have a typical eShopping cart project, I need to show customer the list of products with details, allow customers to pick and order, on the backend I maintain SQL server database to keep updating the inventory and other tables when customers order things. I don't see where I can take advantage of generic class feature for such a common real project ? Any thought ?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One easy and very productive way to use them is to specify types in collections. Let's go print all the shoes in the database:

Generics can make this a lot shorter. We write getProducts() to return List<Product>.

This is shorter, easier to read and safer. The compiler can now assure us that nobody can put anything in that List that is not a Product, so we can't get casting exceptions.

So there's one way to use generics to improve your life. Is that worth the effort for you?
 
Adam Schaible
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are a few different angles of generics.

Using generics to specify types in a collection is a convenience feature when you use specifics, ie:




This is what I call a "consumer" of Java generics.

On the other hand, generics allow you to perform type-based logic where type is not known until runtime.

Lets say you have a specific type of product that you wish to remove from your collection - you could write a specific method that removes all "Gift" objects from the collection, or you could write a method that would allow you to remove whatever type the method caller wishes:





Type information is maintained, and you get the Gift objects out of the list.
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Adam Schaible:

Just a tad more easy to read, and removes the cast warning.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic