Java Reference
In-Depth Information
return "ListItem " + item ;
}
ListItem next; // Refers to next item in the list
T item;
// The item for this ListItem
}
}
The bold lines reflect changes to the original LinkedList class definition that you created in Chapter 6.
Each of the lines that have been modified in the body of the generic type definition replace type Object by
the type variable, T . The item field in the ListItem inner class is now of type T , for example, and the return
type for the getNext() method is also type T . All the methods that use the parameter T in their definitions
are customized by the argument type that is supplied for T when you define a type from the generic type. A
generic type can include ordinary methods that do not involve any parameters in their definitions. This just
means that the ordinary methods are not customized for particular instances of the generic type.
You now have a generic LinkedList<T> type that you can use to create a new LinkedList class for stor-
ing objects of any type that you want. Let's look at how you use it.
Instantiating a Generic Type
You use the generic type name followed by a class or interface type name between angled brackets to define
a new type. For example:
LinkedList<String> strings; // A variable of type LinkedList<String>
This declares a variable with the name strings of type LinkedList<String> , which is from the generic
type that you defined in the previous section. The compiler uses the type argument String that you supplied
to replace every instance of the type variable, T , in the generic type definition to arrive at the notional class
type definition for LinkedList<String> .
Of course, you can initialize an object when you declare the variable, like this:
LinkedList<String> strings = new LinkedList<String>();
This calls the default constructor for the LinkedList<String> class type to define an object that imple-
ments a linked list of String objects. A reference to this object is stored in strings .
There's some redundancy in the previous statement. The type of the strings variable determines the
type of elements that the list it references can store, and this information is repeated on the right side of the
statement. You can avoid typing the list element type twice by writing the statement as:
LinkedList<String> strings = new LinkedList<>();
NOTE The angled brackets without a type specification between are often referred to as the
diamond operator, although it ' s not really an operator within the Java language. If you in-
Search WWH ::




Custom Search