- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Where exactly Type-Parameter need to be specified, while declaring generic method 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.
Example
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
Advertisements