aspose file tools*
The moose likes Beginning Java and the fly likes Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generics" Watch "Generics" New topic
Author

Generics

Swapna latha
Ranch Hand

Joined: Dec 18, 2011
Posts: 70
hi all !

I am confused in generics tutorial or topic. I am not having clear idea. Can anybody suggest which pdf or textbook or site is good to learn generics in detail

Thanks & Regards
Kori Swapna Latha

Riaan Nel
Ranch Hand

Joined: Apr 23, 2009
Posts: 160

Which part of it don't you understand?

Start by writing some code using generics, and once you get stuck, post your code and tell us which part doesn't make sense.


"The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man." - George Bernard Shaw
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14269
    
  21

Generics are meant to make your code more type-safe. Suppose that you have a list of numbers in a program. You can store those numbers in a plain List, but nothing is preventing you from storing something that's not a number in the list:

That can ofcourse lead to problems when you run the program. If you would, for example, make a method that adds all the numbers in the list, it would crash with a ClassCastException when there is something that is not a number in the list.

When you use generics, you can tell the compiler up front that the list is supposed to contain only Integer objects. If you then try to put something in the list that is not an integer, then the compiler will stop with an error. It's always much better to get an error from the compiler when something is wrong than when you don't notice the problem until you run the program.

You can now write your sum method so that it will only accept a list that contains only Integer objects. You can get rid of the cast and make the code easier to read by using the for-each syntax (also making use of auto-unboxing):


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Swapna latha
Ranch Hand

Joined: Dec 18, 2011
Posts: 70
Thank you riaan and jesper.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics