13.1. What Are Generic Types?

A generic type, which is also referred to as a parameterized type, is a class or interface type definition that has one or more type parameters. You define an actual class or interface type from a generic type by supplying a type argument for each of the type parameters that the generic type has. It'll be easier to understand what this means with a concrete example of where and how you could apply the concept.

I'm sure you recall the LinkedList class that you first saw in Chapter 6 and used in an example in the previous chapter. You used the LinkedList class to encapsulate a linked list of Point objects, but the idea of a linked list applies to any set of objects that you want to organize in this way. A linked list is just one example of classes that define objects for organizing other objects of a given type into a collection in some way. Such classes are described as collection classes for obvious reasons, and in Chapter 14 you'll meet a variety of these that are defined in the java.util package.

The LinkedList class that you implemented in Chapter 6 can organize objects of any given type into a linked list. This clearly has the advantage that the code for a single class defines a linked list class that you can use for objects of any kind, but it has significant disadvantages, too. When you were adding Point objects to a LinkedList object, nothing in the code prevented you from adding a Line object, or indeed any type of object, to the same linked ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.