Lesson 12Introduction to Generics

In the previous lesson you saw an example of a collection that stores objects of different types (see Listing 11-2). During the run time, that program would test the actual type of each object and cast it to an appropriate type—Customer or Order. If some code adds an element of another (unexpected) data type, this will result in a casting error, ClassCastException. Instead of leaving it until run time, it would be nice if during the compilation the compiler would prevent using unexpected types with collection, objects, or even method arguments and return types. 

Java supports generics, which enable you to use parameterized data types—you can declare an object, collection, or method without specifying a concrete data type, shifting the definition of concrete types to the code that will use these objects, collections, or methods. In other words, a generic type is one that can work with parameterized data types. 

By using generic notation, you get help from Java compiler, which does not allow you to use objects of the “wrong” types that don’t match the declaration. In other words, you can catch improper data types earlier, during the compilation phase. This concept is easier to explain by examples, and so we’ll get right into it.

Generics ...

Get Java Programming 24-Hour Trainer, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.