Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 14: Generics 335


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 examineisIn( )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 declaredbeforethe return type of the method. Second, notice that
the typeVis upper-bounded byT. Thus,Vmust either be the same as typeT, or a subclass
ofT. This relationship enforces thatisIn( )can be called only with arguments that are compatible
with each other. Also notice thatisIn( )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.

Free download pdf