Java Reference
In-Depth Information
PITFALL: An Instantiation of a Generic Class Cannot be
an Array Base Type
Arrays such as the following are illegal (the generic class
Pair
is the one defined in
Display 14.5 ):
Pair<String>[] a =
new
Pair<String>[10];
//Illegal
This is a reasonable thing to want to do, but it is not allowed because of technical
details having to do with how Java implements generic classes. The full explanation
for this restriction is beyond the scope of this topic.
■
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);
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 }
Automatic boxing allows you
to use an
int
argument for
an
Integer
parameter.