Introduction to Generics
In the previous lesson you saw an example of a collection that stores objects of different types (see Listing 14-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, IllegalCastException.
Starting from Java 5 you can use generics, which enables 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 be using these objects, collections, or methods. And the good part is that by using such generic notation you’ll get help from Java compiler, which will 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.
Generics with Classes
Not only Java methods can have parameters, but classes can have them as well. Consider the ArrayList from Listing 14-2, which is a kitchen sink–like storage that can hold pretty much any object. But if you add the parameterized type Customer in angle brackets to the declaration of the customers collection (see Listing 15-1), any attempt to place an Order object there will generate the following compiler error:
The method add(Customer) in the type ArrayList<Customer> is not applicable for ...