Datasheet

oldVector = intVector;
// This causes an unchecked warning
intVector = oldVector;
// This is permitted
ue.processIntVector(intVector);
// This causes an unchecked warning
ue.processIntVector(oldVector);
}
}
Attempting to compile the previous code leads to the following compiler warnings:
UncheckedExample.java:16: warning: unchecked assignment: java.util.Vector to
java.util.Vector<java.lang.Integer>
intVector = oldVector; // This causes an unchecked warning
UncheckedExample.java:18: warning: unchecked method invocation:
processIntVector(java.util.Vector<java.lang.Integer>) in UncheckedExample is
applied to (java.util.Vector)
ue.processIntVector(oldVector); // This causes an unchecked warning
2 warnings
Wildcards and Bounded Type Variables
Because you can’t use CustomHolder<Object> as if it were a super-type of CustomHolder<String>, you
can’t write a method that would process both
CustomHolder<Object> and CustomHolder<String>.
There is, however, a special way to accomplish this. As part of the generics syntax, a wildcard is intro-
duced, which, when used, basically means “any type parameter.” Revisit the previous example and
show how the wildcard, a single question mark, is used.
Take the
CustomHolder class and add a few new methods and a new main as follows:
public static void processHolderObject(CustomHolder2<Object> holder)
{
Object obj = holder.getItem();
System.out.println(“Item is: “ + obj);
}
public static void processHolderString(CustomHolder2<String> holder)
{
Object obj = holder.getItem();
System.out.println(“Item is: “ + obj);
}
public static void processHolderWildcard (CustomHolder2<?> holder)
{
Object obj = holder.getItem();
System.out.println(“Item is: “ + obj);
11
Chapter 1: Key Java Language Features and Libraries
05_777106 ch01.qxp 11/28/06 10:43 PM Page 11