How to write a Generic method in Java

A method is called generic method if you can pass any type of parameter to it and it will function the same e.g. it allows the same logic to be applied to different types. It's known as a type-safe method as well.


1) You can declare Generic methods not only on Generic or parameterized class but also on regular classes which not generic.

2) The type declaration like <T> should come after modifiers like public static but before return type like the void, int, or float. Here is an example of a generic or parameterized method declaration

public static <T> void swap(T a, T b){

}


3) You can also use bounds with types while declaring Generic methods e.g. T extends Comparable to access the compareTo() method defined in Comparable class. For example, in the following method you can only pass a List of Comparable, List of any class which doesn't implement Comparable is not acceptable

public static void sort(List<T extends Comparable> aList){

}

with respect of this method, following is legal because String implements Comparable
List<String> abcd = Arrays.asList("ab", "bc", "cd");
sort(abcd);

but following is illegal because PrintStream doesn't implement Comparable
List<PrintStream> destinations = new ArrayList<>();

How to write a Generic method in Java



That's all about how to declare a generic or parameterized method in Java. It's one of the important concepts to understand and master because it will help you to write better code and reduce duplicate and boilerplate coding. The fact that you can have generic methods on regular classes also help a lot. This also means you can include new parameterized methods in your existing utility classes.

No comments:

Post a Comment