SoFunction
Updated on 2025-04-07

Custom generic methods and their application example code in Java

Generics is a powerful feature in Java that allows us to use type parameters when writing code, thereby improving the reusability and type safety of our code. Generics can be applied not only to classes, but also to methods. This article will introduce in detail how to define and use custom generic methods in Java and demonstrate their advantages through practical application scenarios.

1. What is a generic method?

A generic method refers to a method that uses type parameters in a method declaration. Unlike generic classes, the type parameters of a generic method are only valid in this method. Generic methods can be defined in normal classes, generic classes, or interfaces.

1.1 Syntax of generic methods

public <T> void genericMethod(T param) {
    // Method body}

In the above code,<T>Represents the type parameter,Tis the name of the type parameter (can be any identifier).TCan be used in the parameters, return type, or method body of the method.

1.2 Sample Code

public class GenericMethodExample {
    // Define a generic method    public &lt;T&gt; void printArray(T[] array) {
        for (T element : array) {
            (element + " ");
        }
        ();
    }
    public static void main(String[] args) {
        GenericMethodExample example = new GenericMethodExample();
        // Print an array of integers using generic methods        Integer[] intArray = {1, 2, 3, 4, 5};
        (intArray);
        // Use generic method to print string array        String[] strArray = {"Hello", "World"};
        (strArray);
    }
}

In this example,printArrayA method is a generic method that can accept arrays of any type and print their elements.

2. Type inference of generic methods

Java compilers can automatically infer the type parameters of a generic method based on the context, so when using generic methods, it is usually not necessary to explicitly specify type parameters.

2.1 Sample Code

public class TypeInferenceExample {
    // Define a generic method    public static &lt;T&gt; T getFirstElement(T[] array) {
        if (array == null ||  == 0) {
            return null;
        }
        return array[0];
    }
    public static void main(String[] args) {
        Integer[] intArray = {1, 2, 3};
        String[] strArray = {"Hello", "World"};
        // The compiler automatically infers the type to Integer        Integer firstInt = getFirstElement(intArray);
        ("First Integer: " + firstInt);
        // The compiler automatically infers the type to String        String firstStr = getFirstElement(strArray);
        ("First String: " + firstStr);
    }
}

In this example, the compiler automatically infers the incoming array type based on the incoming array typegetFirstElementThe type parameter of the method.

3. Type parameter limitations of generic methods

Sometimes we want the type parameters of a generic method to be only certain types or subtypes. At this time, you can use Bounded Type Parameters to limit the range of type parameters.

3.1 Sample Code

public class BoundedTypeParameterExample {
    // Define a generic method, the type parameter must be Number or its subclass    public static &lt;T extends Number&gt; double sum(T[] array) {
        double sum = 0.0;
        for (T element : array) {
            sum += ();
        }
        return sum;
    }
    public static void main(String[] args) {
        Integer[] intArray = {1, 2, 3};
        Double[] doubleArray = {1.1, 2.2, 3.3};
        // Calculate the sum of integer arrays        ("Sum of integers: " + sum(intArray));
        // Calculate the sum of double precision floating point arrays        ("Sum of doubles: " + sum(doubleArray));
    }
}

In this example,sumMethod type parametersTRestricted toNumberor its subclass, so it can be calleddoubleValueMethod converts array elements todoubleTypes and sum.

4. Practical application of generic methods

Generic methods have a wide range of application scenarios in actual development. The following are some common application examples.

4.1 Collection Tool Class

Generic methods are often used to write general collection tool classes, such as sorting, searching, filtering and other operations on collections.

import ;
import ;
public class CollectionUtils {
    // Define a generic method to filter elements in a collection    public static &lt;T&gt; List&lt;T&gt; filter(List&lt;T&gt; list, Predicate&lt;T&gt; predicate) {
        List&lt;T&gt; result = new ArrayList&lt;&gt;();
        for (T element : list) {
            if ((element)) {
                (element);
            }
        }
        return result;
    }
    public static void main(String[] args) {
        List&lt;Integer&gt; numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        // Filter out even numbers        List&lt;Integer&gt; evenNumbers = filter(numbers, n -&gt; n % 2 == 0);
        ("Even numbers: " + evenNumbers);
    }
}
// Define a functional interfaceinterface Predicate&lt;T&gt; {
    boolean test(T t);
}

In this example,filterA method is a generic method that accepts a list and a predicate (Predicate) and return a list of elements that satisfy the predicate condition.

4.2 General Comparator

Generic methods can also be used to write general comparators, such as comparing the size or equality of two objects.

public class ComparatorUtils {
    // Define a generic method to compare the size of two objects    public static &lt;T extends Comparable&lt;T&gt;&gt; int compare(T a, T b) {
        return (b);
    }
    public static void main(String[] args) {
        Integer a = 10;
        Integer b = 20;
        // Compare the size of two integers        int result = compare(a, b);
        ("Comparison result: " + result);
    }
}

In this example,compareThe method is a generic method that accepts two implementationsComparableThe interface object and return their comparison results.

4.3 General factory method

Generic methods can also be used to write common factory methods, such as creating objects of a specific type.

public class FactoryUtils {
    // Define a generic method to create an object    public static &lt;T&gt; T createInstance(Class&lt;T&gt; clazz) {
        try {
            return ().newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create instance", e);
        }
    }
    public static void main(String[] args) {
        // Create a String object        String str = createInstance();
        ("Created string: " + str);
        // Create an ArrayList object        ArrayList&lt;Integer&gt; list = createInstance();
        (1);
        (2);
        ("Created list: " + list);
    }
}

In this example,createInstanceA method is a generic method that accepts aClassobject and return an instance of the class.

5. Summary

Generic methods are a very powerful feature in Java, which allows us to use type parameters at the method level, thereby improving code reusability and type safety. Through the introduction of this article, you should have mastered how to define and use generic methods, and understand the application scenarios of generic methods in actual development.

Generic methods can not only be used to deal with common tasks such as collections, comparison objects, and creating instances, but also limit the scope of type parameters through bounded type parameters, thereby writing more secure and flexible code. Hope this article will be helpful for you to understand and use generic methods! If you have any questions or suggestions, please leave a message in the comment section to discuss.

This is the article about custom generic methods and application sample code in Java. For more related java custom generic content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!