posted 12 years ago
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):