Index

Overview


In addition to coding a generic class, we can also code generics at the method level (on a specific method).

These generic parameters, specified for a specific method, are usable only in the given method. The method may be instance or static.

Here is a simple example just to show format.
The generic parameter (in this case "S") is added near the start of the method header (before the return type).

Generics may be coded on an instance or static method.
private void simpleDemo()  {
	genericMethod(10);
	genericMethod("Hello");
	genericMethod(true);
	genericMethod(101.4);
}

private <S> void genericMethod(S arg)  {
	System.out.println(arg.toString());
}


Example 2


In this example we use generics to compute the min and max of a type that varies. We put a contraint on the type that it must be a "Comparable":
T extends Comparable<T>
. In other words, T "is-a" Comparable.

The example output is:




Max of 20, 30 and 10 = 30
Max of 40.9, 20.9 and 30.8 = 40.9
Max of Boo, Too and Moo = Too
Min of 40.9, 20.9 and 30.8 = 20.9
Press any key to continue . . .

public static void main(String[] args)  {

	//(new GenericMethodDemo()).simpleDemo();

	System.out.printf("%nMax of %d, %d and %d = %d%n", 20, 30, 10,
						maximum(20, 30, 10));

	System.out.printf("Max of %.1f, %.1f and %.1f = %.1f%n", 40.9, 20.9, 30.8,
						maximum(40.9, 20.9, 30.8));

	System.out.printf("Max of %s, %s and %s = %s%n", "Boo", "Too", "Moo",
						maximum("Boo", "Too", "Moo"));

	System.out.printf("Min of %.1f, %.1f and %.1f = %.1f%n", 40.9, 20.9, 30.8,
						minimum(40.9, 20.9, 30.8));
}

public static <T extends Comparable<T>> T maximum(T a, T b, T c)  {
	T max = a;
	if (b.compareTo(max) > 0)
		max = b;
	if (c.compareTo(max) > 0)
		max = c;
	return max;
}

public static <T extends Comparable<T>> T minimum(T a, T b, T c)  {
	T min = a;
	if (b.compareTo(min) < 0)
		min = b;
	if (c.compareTo(min) < 0)
		min = c;
	return min;
}



References