for(int i=0; i < y.length; i++)
if(x.equals(y[i])) return true;
return false;
}
public static void main(String args[]) {
// Use isIn() on Integers.
Integer nums[] = { 1, 2, 3, 4, 5 };
if(isIn(2, nums))
System.out.println("2 is in nums");
if(!isIn(7, nums))
System.out.println("7 is not in nums");
System.out.println();
// Use isIn() on Strings.
String strs[] = { "one", "two", "three",
"four", "five" };
if(isIn("two", strs))
System.out.println("two is in strs");
if(!isIn("seven", strs))
System.out.println("seven is not in strs");
// Oops! Won't compile! Types must be compatible.
//
if(isIn("two", nums))
//
System.out.println("two is in strs");
}
}
The output from the program is shown here:
2 is in nums
7 is not in nums
two is in strs
seven is not in strs
Let's examine isIn( ) closely. First, notice how it is declared by this line:
static <T, V extends T> boolean isIn(T x, V[] y) {
The type parameters are declared before the return type of the method. Second, notice that
the type V is upper-bounded by T. Thus, V must either be the same as type T, or a subclass
of T. This relationship enforces that isIn( ) can be called only with arguments that are compatible
with each other. Also notice that isIn( ) is static, enabling it to be called independently of any
object. Understand, though, that generic methods can be either static or non-static. There is
no restriction in this regard.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home