Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

9.2 Generic methods — a method with its own type parameter

Lesson

Generics without a generic class

A single method can be generic even when its class is not. Declare the type parameter before the return type: public static <T> int count(T[] arr, T target). Then T is available throughout that method. You almost never write the type at the call site — Java infers it from the arguments.


Worked example

public static <T> int count(T[] arr, T target) {
    int count = 0;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i].equals(target)) {   // equals works for any object
            count++;
        }
    }
    return count;
}

String[] names = {"Ada", "Sam", "Ada"};
System.out.println(Util.count(names, "Ada"));   // 2 — T inferred as String

The same method also counts Integers, or anything else — one method, every type.


▶ Try it: run this — printAll and count are generic methods used with Strings and Integers.



Where does a generic method declare its type parameter?


When you call Util.count(names, "Ada"), the type T is...


Type exactly what this program prints.

class U {
    public static <T> int count(T[] arr, T t) {
        int c = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].equals(t)) { c++; }
        }
        return c;
    }
}
public class Main { public static void main(String[] a){
    String[] w = {"a", "b", "a", "a"};
    System.out.println(U.count(w, "a"));
}}

To compare two objects for equality inside a generic method, use...


True or false?