Skip to content

Generic Methods

The Course
•
20 min study

A method can introduce its own type parameter even when its surrounding class is not generic. Use this when one operation works across several element types and must return a value of the same type. Put the type parameter before the method's return type.

Work through the example

In static <T> T first(List<T> values), T links the list element type to the result. The caller does not receive Object. The compiler normally infers T from the argument. The explicit empty check is a runtime contract: generic typing does not make a list nonempty.

This method returns an existing reference. It does not copy or remove the element. Stating that ownership rule matters if the elements can change. A generic method should have behavior that makes sense for every allowed T, not rely on a hidden assumption that T is always String.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<String> titles = new ArrayList<>();
        titles.add("Read");
        List<Integer> durations = new ArrayList<>();
        durations.add(25);
        System.out.println(first(titles).length());
        System.out.println(first(durations) + 5);
    }

    static <T> T first(List<T> values) {
        if (values.isEmpty()) {
            throw new IllegalArgumentException("nonempty list required");
        }
        return values.get(0);
    }
}
Check your prediction
Text
4
30

Compare the behavior

A copy method keeps the element type while returning a new container. The method signature says that copying a List<String> produces a List<String>, without casts. It still makes only a shallow copy; generics do not provide deep cloning.

Trace the changed case Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<String> source = new ArrayList<>();
        source.add("Read");
        List<String> result = copy(source);
        result.clear();
        System.out.println(source);
        System.out.println(result);
    }

    static <T> List<T> copy(List<T> source) {
        return new ArrayList<>(source);
    }
}
Check your prediction
Text
[Read]
[]

Read the signature before the implementation

In static <T> T first(List<T> values), the initial <T> declares a method type parameter, the next T is the result type, and List<T> supplies the connection to the argument. The compiler can infer a separate T for each call. Main itself does not need to be a generic class.

A type-correct signature leaves runtime decisions open. What happens on an empty list? Can elements be null? Is the returned element copied? Today's first and last methods reject empty input, read nonnull lists, and return an existing element reference without editing membership. State these rules separately from type safety.

A one-element list is especially useful: first and last both select index zero. A two-element list distinguishes them. An empty list checks the guard. Choose all three cases instead of testing many longer lists with the same easy outcome.

Debug a plausible mistake

Generic typing preserves a relationship, but cannot prove an index expresses the intended algorithm. A wrong first-element implementation is perfectly type-safe. Use different first and last values so the behavioral defect becomes visible. List.of(...) is a library factory for a fixed unmodifiable list; it rejects null elements. This read-only lookup accepts it because it does not edit its input.

Exercise

Repair the generic last element

last must return the final element while preserving its type. Print Test and 25 for the two calls. Keep empty-input rejection. Predict what the current program actually prints before changing it, make the smallest repair, then also try a one-element list. The supplied version compiles; its behavior is the problem.

Debugging workspace Java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        System.out.println(last(List.of("Read", "Test")));
        System.out.println(last(List.of(10, 25)));
    }

    static <T> T last(List<T> values) {
        if (values.isEmpty()) {
            throw new IllegalArgumentException("nonempty list required");
        }
        return values.get(0);
    }
}
Hint 1: the idea

Type correctness and position correctness are separate promises.

Hint 2: a first step

The final valid index is one less than the number of elements.

Show one solution
Java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        System.out.println(last(List.of("Read", "Test")));
        System.out.println(last(List.of(10, 25)));
    }

    static <T> T last(List<T> values) {
        if (values.isEmpty()) {
            throw new IllegalArgumentException("nonempty list required");
        }
        return values.get(values.size() - 1);
    }
}

Expected output after repair:

Text
Test
25

The bug was values.get(0), which compiled happily because the first element is a T just as much as the last one is; the program printed Read and 10. The type checker proves "you return a T", not "you return the right T". A one-element list hides the bug (first and last are the same element), which is why the brief's lists have two different values.

Practice independently

Exercise

Generic Methods: practice

last read a T out of a list. Now write a generic method that builds a list: repeat(T value, int times) returns a new list holding value times times. Reject a negative count with times must be nonnegative. Show that the result's element type follows the argument: a List<String> from "Go" and a List<Integer> from 5, and that the String result can call a String method on its elements without a cast.

Text
[Go, Go, Go]
[5, 5]
2
[]
times must be nonnegative

The 2 is repeat("Go", 3).get(0).length().

Your workspace Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        System.out.println("Implement generic repeat");
    }
}
Hint 1: the idea

The method's type parameter has to link the argument to the list it returns: whatever type value has, the returned list holds that type. That link is what lets the caller use .length() on an element with no cast.

Hint 2: a first step

Write the signature first: static <T> List<T> repeat(T value, int times). Inside, create a new ArrayList<T>() and add value in a loop that runs times times.

Show one solution
Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<String> words = repeat("Go", 3);
        List<Integer> numbers = repeat(5, 2);

        System.out.println(words);
        System.out.println(numbers);
        System.out.println(words.get(0).length());
        System.out.println(repeat("x", 0));

        try {
            repeat("x", -1);
        } catch (IllegalArgumentException error) {
            System.out.println(error.getMessage());
        }
    }

    static <T> List<T> repeat(T value, int times) {
        if (times < 0) {
            throw new IllegalArgumentException("times must be nonnegative");
        }
        List<T> result = new ArrayList<>();
        for (int i = 0; i < times; i++) {
            result.add(value);
        }
        return result;
    }
}

Expected output:

Text
[Go, Go, Go]
[5, 5]
2
[]
times must be nonnegative

The <T> before the return type declares the method's own type parameter, and List<T> in the return type ties the result to the argument. That is why words is a List<String> and .length() compiles. Had the method returned List<Object>, the caller would need a cast to use any String method. A count of 0 is valid and returns an empty list; only a negative count is an error.

Change it and test again

Change repeat's return type to List<Object> (and the list it creates). Which line in main stops compiling, and why? Restore it. Then write first(List<T>) to match last, and decide what it should do with an empty list.

Explain before moving on

Which T belongs to the method rather than a class? Why is returning Object a weaker contract than returning T?

Was this article helpful?

Your response is saved on this device.