jQuery in Action, 3rd edition
The moose likes Java in General and the fly likes don't see how generic class is useful in common cases Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "don Watch "don New topic

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

Raj Ohadi
Ranch Hand

Joined: Jun 30, 2006
Posts: 316
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

Joined: Jan 29, 2003
Posts: 8791
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?

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Adam Schaible
Ranch Hand

Joined: Oct 04, 2007
Posts: 101
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

Joined: Oct 27, 2005
Posts: 20273

Originally posted by Adam Schaible:

Just a tad more easy to read, and removes the cast warning.

How To Ask Questions How To Answer Questions
I agree. Here's the link: http://aspose.com/file-tools
subject: don't see how generic class is useful in common cases
It's not a secret anymore!