Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics

 
Swapna latha
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 160
IntelliJ IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15490
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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):

 
Swapna latha
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you riaan and jesper.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic