Java Reference
In-Depth Information
S YNTAX 17.1 Instantiating a Generic Class
GenericClassName<Type 1 , Type 2 , . . . >
Example:
ArrayList<BankAccount>
HashMap<String, Integer>
Purpose:
To supply specific types for the type variables of a generic class
767
768
S ELF C HECK
1. The standard library provides a class HashMap<K, V> with key type
K and value type V . Declare a hash map that maps strings to integers.
2. The binary search tree class in Chapter 16 is an example of generic
programming because you can use it with any classes that implement the
Comparable interface. Does it achieve genericity through inheritance
or type variables?
17.2 Implementing Generic Classes
In this section, you will learn how to implement your own generic classes. We will
first start out with a very simple generic class that stores pairs of objects. Then we
will turn the LinkedList class of Chapter 15 into a generic class.
Our first example for writing a generic class stores pairs of objects, each of which can
have an arbitrary type. For example,
Pair<String, BankAccount> result
= new Pair<String, BankAccount>(ÐHarry
HackerÑ, harrysChecking);
The getFirst and getSecond methods retrieve the first and second values of the
pair.
String name = result.getFirst();
Search WWH ::




Custom Search