How do I create a generic method in Java?

A generic method uses a type parameter to work with different reference types. This lets you reuse the same method without writing a separate version for each type.

In this example, you will create a method that prints the elements of an array. The same method will handle arrays of strings and integers.

Source code

Save the following code as GenericMethodExample.java:

public class GenericMethodExample {
    void main() {
        String[] languages = {"Java", "Python", "JavaScript"};
        Integer[] numbers = {10, 20, 30};

        IO.println("Languages:");
        printElements(languages);

        IO.println();
        IO.println("Numbers:");
        printElements(numbers);
    }

    <T> void printElements(T[] elements) {
        for (T element : elements) {
            IO.println(element);
        }
    }
}

Explanation

The printElements() method declares a type parameter named T:

<T> void printElements(T[] elements) {
    for (T element : elements) {
        IO.println(element);
    }
}

The <T> declaration appears before the return type, void. It makes T available as a type within the method declaration and body.

Each part has a purpose:

Part Purpose
<T> Declares the type parameter
void Indicates that the method does not return a value
T[] elements Accepts an array whose element type is T
T element Holds each element during iteration

T is a conventional name. You can use a more descriptive name when it makes the code easier to understand.

Calling the method with different types

The first call passes an array of strings:

String[] languages = {"Java", "Python", "JavaScript"};
printElements(languages);

The compiler infers T as String for this call.

The second call passes an array of integers:

Integer[] numbers = {10, 20, 30};
printElements(numbers);

For this call, the compiler infers T as Integer.

You do not need to specify the type argument explicitly because the compiler can infer it from the array argument.

Using wrapper types

Java generic type arguments must be reference types. You cannot use a primitive type such as int as the type argument for T.

That is why this example uses Integer[] rather than int[]. Autoboxing converts the integer literals into Integer objects when the array is initialized.

Passing an int[] directly to this method would cause a compilation error.

Run the example

Compile and run the file:

javac GenericMethodExample.java
java GenericMethodExample

Output

Languages:
Java
Python
JavaScript

Numbers:
10
20
30

The type parameter belongs to the method, so the containing class does not need to be generic. Use a generic method when the same operation can work with multiple types while keeping compile-time type checking.

Leave a Comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.