Java Reference
In-Depth Information
Display 14.9
Using a Generic Class with Two Type Parameters
1 import java.util.Scanner;
2 public class TwoTypePairDemo
3 {
4 public static void main(String[] args)
5 {
6 TwoTypePair<String, Integer> rating =
7 new TwoTypePair<String, Integer>("The Car Guys", 8);
8 Scanner keyboard = new Scanner(System.in);
9 System.out.println(
10 "Our current rating for " + rating.getFirst());
11 System.out.println(" is " + rating.getSecond());
12 System.out.println("How would you rate them?");
13 int score = keyboard.nextInt();
14 rating.setSecond(score);
15 System.out.println(
16 "Our new rating for " + rating.getFirst());
17 System.out.println(" is " + rating.getSecond());
18 }
19 }
Sample Dialogue
Our current rating for The Car Guys
is 8
How would you rate them?
10
Our new rating for The Car Guys
is 10
Bounds for Type Parameters
Sometimes it does not make sense to plug in just any reference type for the type
parameter in a generic class definition. For example, consider the generic class Pair
defined in Display 14.5. Suppose we want to add a method that returns the maximum
of the two elements in an ordered pair. We could add the following method definition
to the class Pair in Display 14.5 :
max
public T max()
{
if (first.compareTo(second) <= 0)
return first;
else
return second;
}
 
 
Search WWH ::




Custom Search