Sub topic 13
Write Generic Methods
A generic method is a method that can work with more than one type while keeping type checks. A type describes what kind of value something can hold, such as text or a whole number.
Generic methods are useful when the same steps work for different types. Instead of writing one method for text and another for numbers, you can write one generic method.
This chapter assumes you have already used Java methods, parameters, return values, arrays, and objects.
Use a type parameter
A type parameter is a placeholder for a type. Java often uses the name T for it, but you can choose another valid name.
Here is a complete program. Save it as GenericMethods.java.
class GenericMethods {
static <T> T firstOrDefault(T[] items, T fallback) {
if (items.length == 0) {
return fallback;
}
return items[0];
}
public static void main(String[] args) {
String[] names = {"Ava", "Ben"};
Integer[] scores = {};
String name = firstOrDefault(names, "Nobody");
Integer score = firstOrDefault(scores, 0);
System.out.println(name);
System.out.println(score);
String explicitName =
GenericMethods.<String>firstOrDefault(names, "Nobody");
System.out.println(explicitName);
}
}Compile and run it with javac GenericMethods.java and java GenericMethods. It prints Ava, then 0, then Ava, each on its own line.
Read the declaration
A declaration is the code that names and describes a method. Look at the first line of this method:
static <T> T firstOrDefault(T[] items, T fallback)
| Part | Meaning |
|---|---|
| `static` | The method belongs to the class, so you do not need an object to call it. |
| `<T>` | The method declares a type parameter named `T`. |
| `T` | The method returns a value of type `T`. |
| `T[] items` | The first parameter is an array whose elements have type `T`. |
| `T fallback` | The second parameter has type `T`. |
An array is a group of elements stored in order. In this example, the method returns the first element when the array has one. When the array is empty, it returns the fallback.
The <T> before the return type is important. It declares T so the rest of the method can use it. The T after it describes the return type.
Follow the two calls
A call is a request to run a method. An argument is a value supplied in a call. A parameter is the named place that receives an argument.
In the first call, names and "Nobody" are arguments:
String name = firstOrDefault(names, "Nobody");
The array holds String values, and the fallback is also a String. Java uses String for T. The method returns "Ava", which is stored in name.
In the second call, scores is an empty array of Integer values. An Integer is an object that holds a whole-number int value. Java turns the argument 0 into an Integer for this call. Because the array is empty, the method returns that fallback.
The method’s steps are the same in both calls. The type parameter lets those steps work with either type.
How Java chooses the type
Type inference is Java’s process of working out a type from the code around it. The compiler is the tool that checks Java code and turns it into a form the computer can run.
In the first two calls, the compiler infers T. The third call supplies the type explicitly:
GenericMethods.<String>firstOrDefault(names, "Nobody")
Here, <String> tells Java to use String for T. You usually do not need to write it because inference can work it out.
A type parameter helps Java check that values fit together. For example, String name = firstOrDefault(names, 0); does not compile: the fallback is a number, but the result must fit in a String.
Sometimes Java can choose a broader type that fits different arguments. Do not assume that every argument to a generic method must always have the exact same type.
Reference types and primitives
A reference type is a type whose values refer to objects. String and Integer are reference types. A primitive type is a basic Java value type, such as int or double.
A type argument is the type used in place of a type parameter. Type arguments must be reference types. You cannot use int as the type argument T.
Use Integer when you need a whole-number type with a generic method. Integer is a wrapper type: it wraps an int value in an object. Java can often perform the wrapping for you, as it did with 0 in the example.
An int[] cannot be passed to firstOrDefault as its T[] argument. Use an Integer[] for that call instead.
Limit the types a method accepts
Sometimes a generic method needs to use an ability that not every type has. A bound is a limit on the types that can be used for a type parameter.
The next method needs to compare two values. It uses Comparable, an interface. An interface describes methods that a type can provide. Comparable<T> describes a compareTo method for comparing a value with another value of type T.
Save this program as LargerDemo.java, then compile and run it.
class LargerDemo {
static <T extends Comparable<T>> T larger(T left, T right) {
if (left.compareTo(right) >= 0) {
return left;
}
return right;
}
public static void main(String[] args) {
System.out.println(larger(4, 7));
System.out.println(larger("apple", "pear"));
}
}It prints 7 and then pear.
In <T extends Comparable<T>>, the word extends introduces the bound. The bound lets the method call compareTo on left.
The result of compareTo is:
- Less than zero if
leftcomes beforeright. - Zero if they compare as equal.
- Greater than zero if
leftcomes afterright.
Both Integer and String work with this bound. Numbers are compared by value. Strings use character order, which is not always the same as dictionary order.
Common mistakes
Expecting a fallback for every missing value
In firstOrDefault, the fallback is used only when the array is empty. If the first element is null, the method returns null.
null means that a reference does not refer to an object. The example also expects the array itself to be non-null; it cannot check the length of a null array.
Likewise, the larger example expects non-null values. It calls compareTo on left, which it cannot do if left is null.
Treating `T` as a concrete type
Inside a generic method, T stands for a type supplied by the call. Without a bound, the method cannot assume that a T has number methods or text methods. Add a suitable bound when the method needs a particular ability.
Java removes most type-parameter information when it compiles generic code. This is called type erasure. Among other effects, a generic method cannot create a value with new T() or an array with new T[5]. It can accept a value or array as an argument instead.
Forgetting when a generic method helps
A generic method is most useful when its type parameter connects parts of the method. In firstOrDefault, T connects the array elements, fallback, and result. That connection lets a caller receive a String result from String inputs without having to convert the result.
Practice
Exercise
What does firstOrDefault return for a String array containing "red" and "blue", with "none" as the fallback?
Show answer
It returns "red". The array is not empty, so the method returns its first element.
Exercise
Why does firstOrDefault use Integer[] rather than int[] for an array of whole numbers?
Show answer
T must be a reference type. Integer is a reference type, while int is a primitive type, so int[] cannot be used as the method's T[] argument.
Exercise
In LargerDemo, what does larger("apple", "pear") return, and what allows the method to call compareTo?
Show answer
It returns "pear". The bound T extends Comparable<T> allows the method to call compareTo on values of type T.