don't see how generic class is useful in common cases
Joined: Jun 30, 2006
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 ?
Joined: Jan 29, 2003
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
Joined: Oct 04, 2007
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.