O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

13.2. Defining a Generic Class Type

I'll use the LinkedList class as a model for showing how you define a generic type because you already know how a linked list works. A definition of a generic class type looks very much like the definition of an ordinary class, but with a parameter specification added following the class name. Here's how the LinkedList class from Chapter 6 looks as an outline of a generic type:

public class LinkedList<T> {                     // T is the type parameter
  // Generic type definition...
}

The parameter that appears between the angled brackets, <>, that follows the generic type name, LinkedList, is called a type parameter. The name, T, identifies the type parameter, and you use the parameter name in the definition of the methods and fields in the generic type where there is a dependency on the argument value for this parameter in the implementation detail. Occurrences of the type parameter name in the definition of a generic type are called type variables because they will be replaced by a value that is a type, in a similar way to how method parameters are replaced by the arguments that you supply.

Although I've used a single letter, T, as the type parameter name to indicate that the argument should be a Type, you can use any legal identifier. For example, you could use InsertYourTypeHere as the parameter name, but this would make the code in the body of the generic type definition rather cumbersome. It's generally best to keep the parameter names as short as possible—ideally ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required