- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are generic methods in Java?
Similar to generic classes you can also define generic methods in Java. These methods use their own type parameters. Just like local variables, the scope of the type parameters of the methods lies within the method.
While defining a generic method you need to specify the type parameter within the angle brackets (< T >). This should be placed before the method's return type.
You can have multiple type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.
The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
Example1
public class GenericMethod { <T>void sampleMethod(T[] array) { for(int i=0; i<array.length; i++) { System.out.println(array[i]); } } public static void main(String args[]) { GenericMethod obj = new GenericMethod(); Integer intArray[] = {45, 26, 89, 96}; obj.sampleMethod(intArray); String stringArray[] = {"Krishna", "Raju", "Seema", "Geeta"}; obj.sampleMethod(stringArray); } }
Output
45 26 89 96 Krishna Raju Seema Geeta
Example2
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; public class GenericMethodExample { public static <T> void arrayToCollection(T[] array, Collection<T> coll ) { for(int i=0; i<array.length; i++) { coll.add(array[i]); } System.out.println(coll); } public static void main(String args[]) { Integer [] intArray = {24, 56, 89, 75, 36}; ArrayList<Integer> al1 = new ArrayList<Integer>(); arrayToCollection(intArray, al1); String [] stringArray = {"Ramu", "Raju", "Rajesh", "Ravi", "Roshan"}; ArrayList<String> al2 = new ArrayList<String>(); arrayToCollection(stringArray, al2); } }
Output
[24, 56, 89, 75, 36] [Ramu, Raju, Rajesh, Ravi, Roshan]
- Related Articles
- What are generic methods in C#?
- Generic Methods for DEPQs
- Can we have multiple type parameters in generic methods in Java?
- What are the uses of generic collections in Java?
- What are methods in Java?
- Non-generic Vs Generic Collection in Java
- What are defender methods or virtual methods in Java?
- What are generic features in C#?
- What are generic collections in C#?
- What are generic delegates in C#?
- what are abstract methods in Java?
- What are vararg methods in Java?
- What are Default Methods in Java 8?
- What are Class/Static methods in Java?
- Defining generic method inside Non-generic class in Java

Advertisements