Java Reference
In-Depth Information
TIP: Compile with the -Xlint Option
There are many pitfalls that you can encounter when using type parameters. If you
compile with the -Xlint option, you will receive more informative diagnostics of
any problems or potential problems in your code. For example, the class Sample in
Display 14.4 should be compiled as follows:
javac -Xlint Sample.java
If you are using an IDE to compile your programs, check your documentation to see
how to set compiler options. (For the TextPad environment, you can set compiler
options in the Preferences box under the Configure menu.)
When compiling with the -Xlint option, you will get more warnings than you
would otherwise get. A warning is not an error, and if the compiler gives only warnings
and no error message, then the class has compiled and can be used. However, in most
cases, be sure you understand the warning and feel confi dent that it does not indicate a
problem, or else change your code to eliminate the warning. One warning that you may
get on some programs in this text is “no defi nition of serialVersionUID .” Discussion of
this warning is beyond the scope of this topic, but you can safely ignore the warning.
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 people's 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
constructor 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 next, 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
parameter T , as shown next, 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 next, 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 .
 
Search WWH ::




Custom Search