Generic Methods

Contact Us or call 1-877-932-8228
Generic Methods

Generic Methods

Methods may be generic, whether or not they are in a generic class. The syntax is somewhat ugly, since it requires listing the type variable before the return type and requires that at least one parameter to the method be of the generic type (that is how the compiler knows what the type is).

public <T> T chooseRandomItem(T[] items) {
	Random r = new Random();
	return items[r.nextInt(items.length)];

The above method is parameterized with type T. The type for T is established by whatever type of array is passed in; if we pass in a String array, then T is String. The method will then randomly pick one to return.

The type may be bounded with extends.