Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download a Free Sample PDF

How to write a Parameterized Method in Java using Generics? Example

Hello guys, if you are wondering how to write a parameterized method in Java using Generics then you are at right place. Earlier, I  have shared Complete Java Generics tutorial as well as popular Generics Interview Questions and in this article, I will teach you how to write a parameterized method using Generics in Java step by step. A method is called a generic method if you can pass any type of parameter to it and it will function the same like it allows the same logic to be applied to different types. It's known as a type-safe method as well.


Steps to Create a Parameterized Method using Generics in Java

1) You can declare Generic methods not only on Generic or parameterized classes 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){
  // your code
}


3) You can also use bounds with types while declaring Generic methods like 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){
  // your code
}

with respect to this method, the following code is legal because String implements Comparable:

List<String> abcd = Arrays.asList("ab", "bc", "cd");
sort(abcd);

but the following code is illegal because PrintStream doesn't implement Comparable:

List<PrintStream> destinations = new ArrayList<>();

How to write a Generic method in Java using Generics




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 in regular classes also helps a lot. This also means you can include new parameterized methods in your existing utility classes.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.