How to Write Generic Method in Java?

There are two places where we can declare type parameter, at class level and at method level. We have already discussed Generic classes,however, coming to method level, a method with type parameter placed before return type is termed as generic method which can be declared in both generic and concrete classes.

In simple words, a generic method can be defined as a method declared with type parameter that is capable of handling various argument types. The scope of type parameter is restricted within the particular method in which it is declared.

Similar to Generic Class, we can use type parameter within the method as per our need.

Syntax,

<T> void print(T obj);

Java Program to demonstrate generic method

public class GenericMethodExample {
    public static void main(String[] args) {
        GenericMethodExample obj = new GenericMethodExample();
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("This is an example ");
        arrayList.add("Generic Method ");
        obj.callMe(arrayList);
    }

    private <T> void callMe(ArrayList<T>  arr) {
        System.out.println("Printing Array List elements : ");
        for (T singleElement:
             arr) {
            System.out.println(singleElement);
        }
     }
}

Output:

Printing Array List elements : 
This is an example 
Generic Method

Bounded Type Parameter

A generic method also allows defining bounded type parameter which restricts the acceptable object types.

Syntax,

<T extends Number> void print(T obj);

Java program to demonstrate Bounded Type Parameter

public class GenericMethodExample {
    public static void main(String[] args) {
        GenericMethodExample obj = new GenericMethodExample();
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(3);
        arrayList.add(5);
        obj.callMe(arrayList);
        ArrayList<Double> doubleArrayList = new ArrayList<>();
        doubleArrayList.add(10.0);
        doubleArrayList.add(23.45);
        obj.callMe(doubleArrayList);

    }

    private <T extends Number> void callMe(ArrayList<T> arr) {
        System.out.println("Printing Array List elements : ");
        for (T singleElement :
                arr) {
            System.out.println(singleElement);
        }
    }
}

 

In above example, only Number object and its subclasses are valid to invoke the method, otherwise, compile time error would be triggered by compiler.

Apart from this, the behaviour of an object depends, if a generic object is in non-generic class or method, it would behave like non-generic object. And If non-generic object is passed to generic class or method, it would behave as generic object.

Leave a Reply