Java Reference
In-Depth Information
EXAMPLE:
A Generic Class for Ordered Pairs
In Display 14.5, we have given a parameterized class for ordered pairs of values.
Notice that the constructor heading does not include the type parameter
T
. This is
counter to many peoples' intuition, but that is the way it is done. A constructor can use
the type parameter, such as
T
, as the type for a parameter for the constructor, but the con-
structor heading does not include the type parameter in angular brackets, such as
<T>
.
By using this parameterized class with the type
String
plugged in for the type
parameter
T
, as shown below, you get a class whose objects are pairs of
String
values:
Pair<String> secretPair =
new
Pair<String>("Happy", "Day");
By using this parameterized class with the type
Integer
plugged in for the type param-
eter
T
, as shown below, you get a class whose objects are pairs of
Integer
objects:
Pair<Integer> rollOfDice =
new
Pair<Integer>(
new
Integer(2),
new
Integer(3));
If
Pet
is some class you defined, you can plug in
Pet
for the type parameter
T
, as shown
below, to get a class whose objects are pairs of objects of type
Pet
:
Pet male =
new
Pet();
Pet female =
new
Pet();
<
Some code to set the data for the objects
male
and
female
.
>
Pair<Pet> breedingPair =
new
Pair<Pet>(male, female);
Display 14.6 contains a simple example of using our generic class
Pair
.
Display 14.5
A Generic Ordered Pair Class
(part 1 of 2)
1
public class
Pair<T>
2{
3
Constructor headings do not
include the type parameter in
angular brackets.
private
T first;
4
private
T second;
5
public
Pair()
6
{
7
first =
null
;
8
second =
null
;
9
}
10
public
Pair(T firstItem, T secondItem)
11
{