Java Reference
In-Depth Information
Display 14.7
Using Our Ordered Pair Class and Automatic Boxing
(part 1 of 2)
1
import
java.util.Scanner;
2
public class
GenericPairDemo2
3{
4
public static void
main(String[] args)
5
{
6
Pair<Integer> secretPair =
7
new
Pair<Integer>(42, 24);
Automatic boxing allows you
to use an
int
argument for an
Integer
parameter.
8
9
Scanner keyboard =
new
Scanner(System.in);
10
System.out.println("Enter two numbers:");
11
int
n1 = keyboard.nextInt();
12
int
n2 = keyboard.nextInt();
13
Pair<Integer> inputPair =
14
new
Pair<Integer>(n1, n2);
15
if
(inputPair.equals(secretPair))
16
{
17
System.out.println("You guessed the secret numbers");
18
System.out.println("in the correct order!");
19
}
20
else
21
{
22
System.out.println("You guessed incorrectly.");
23
System.out.println("You guessed");
24
System.out.println(inputPair);
25
System.out.println("The secret numbers are");
26
System.out.println(secretPair);
27
}
28
}
29
}
Sample Dialogue
Enter two numbers:
42 24
You guessed the secret numbers
in the correct order!
TIP: A Class Definition Can Have More Than One Type Parameter
A generic class definition can have any number of type parameters. The multiple type
parameters are listed in angular brackets just as in the single type parameter case, but
are separated by commas. For example, in Display 14.8, we have rewritten the class
Pair
so the first and second items of a pair can be of different types. In Display 14.9,
we give a simple example of using our generic class with two type parameters.
■