Java Programming Handbook

    Generic Methods in Java

    Introduction#

    In the previous blog, we discussed Bounds on Generics, which allow us to restrict the types of parameters in generic classes. But what if we only want to make a single method generic instead of an entire class? This is where Generic Methods come into play.

    In this blog, we will cover:

    • What are Generic Methods?
    • Defining a Generic Method
    • Using Multiple Type Parameters
    • Upper and Lower Bounds in Generic Methods
    • Wildcards in Generic Methods
    • Generic Method vs Generic Class
    • Example Use Cases

    What are Generic Methods?#

    A Generic Method is a method that has its own type parameter, independent of any class-level generics. This allows a method to work with different data types while still maintaining type safety.

    🔹 Syntax of a Generic Method:

    <type_parameter> returnType methodName(parameters) { // method body }
    • <T> before the return type indicates a generic method.
    • T is the type parameter that the method will use.

    Defining a Generic Method#

    Let's create a simple generic method that prints any type of array:

    public class GenericMethodExample { public static <T> void printArray(T[] elements) { for (T element : elements) { System.out.print(element + " "); } System.out.println(); } public static void main(String[] args) { Integer[] intArray = {1, 2, 3, 4, 5}; String[] strArray = {"Hello", "Java", "Generics"}; System.out.println("Integer Array:"); printArray(intArray); System.out.println("String Array:"); printArray(strArray); } }

    Output:#

    Integer Array: 1 2 3 4 5 String Array: Hello Java Generics

    ✅ Here, the printArray method works with both Integer[] and String[], demonstrating the power of generics.

    Using Multiple Type Parameters#

    A generic method can have multiple type parameters.

    Example: Swapping Two Elements of Any Type#

    public class SwapExample { public static <T, U> void swap(T first, U second) { System.out.println("Before Swap: " + first + " and " + second); // Swap logic using a temporary variable U temp = second; second = (U) first; first = (T) temp; System.out.println("After Swap: " + first + " and " + second); } public static void main(String[] args) { swap(10, "Java"); } }

    ✅ This example shows multiple generic types (T and U), allowing the method to work with different data types.

    Upper and Lower Bounds in Generic Methods#

    Sometimes, we may want to restrict the types of values that can be passed to a generic method. This is done using Upper Bounds (extends) and Lower Bounds (super).

    Upper Bound (extends)#

    The extends keyword is used to restrict a generic type to a specific class or its subclasses.

    public class UpperBoundExample { public static <T extends Number> void showNumber(T num) { System.out.println("Number: " + num); } public static void main(String[] args) { showNumber(10); // Works with Integer showNumber(5.5); // Works with Double // showNumber("Java"); // Compile-time error } }

    ✅ Only Number and its subclasses (Integer, Double, Float, etc.) are allowed.

    Lower Bound (super)#

    The super keyword restricts a generic type to a specific class or its superclasses.

    import java.util.List; public class LowerBoundExample { public static void addNumber(List<? super Integer> list) { list.add(10); // ✅ Allowed list.add(20); // ✅ Allowed // list.add(3.5); // ❌ Compile-time error } }

    ✅ The method can accept Integer or any of its superclasses (Number, Object, etc.).

    Wildcards in Generic Methods#

    Wildcards (?) provide flexibility by allowing unknown types.

    Example: Using ? to Print Any List#

    import java.util.List; public class WildcardExample { public static void printList(List<?> list) { for (Object obj : list) { System.out.print(obj + " "); } System.out.println(); } }

    ✅ The method can accept any type of List (List, List, etc.).

    Generic Method vs Generic Class#

    FeatureGeneric ClassGeneric Method
    ScopeThe whole class is genericOnly a specific method is generic
    Type ParametersDefined at class levelDefined within the method
    UsageUseful when multiple methods need genericsUseful when only one method needs generics
    Exampleclass Box<T><T> void method(T param)

    Example Use Cases of Generic Methods#

    1. Utility Methods – Printing arrays, finding maximum/minimum values.
    2. Sorting Algorithms – Implementing generic sorting functions.
    3. Data Conversion – Converting objects from one type to another.
    4. Wildcards & Bounds – Providing flexible methods with constraints.

    Conclusion#

    In this blog, we learned:

    • What Generic Methods are and how they differ from Generic Classes.
    • How to define and use generic methods with single and multiple type parameters.
    • The concepts of Upper Bounds (extends), Lower Bounds (super), and Wildcards (?) in generic methods.
    • Practical use cases of generic methods in real-world programming.

    Generic methods provide flexibility and type safety, making Java code more reusable and efficient.

    Last updated on Apr 09, 2025