Table of Contents
Building Generic Methods
Generic methods in Java, also called general functions, are methods with no fixed arguments list. The argument list can be changed depending on the requirement/purpose of the program. The Java compiler also handles these methods accordingly.
Generic Methods
A generic method declaration can write a single generic method. As mentioned above, this method can be called with varying arguments. There are a few rules governing generic methods in Java. They are as follows:
- All generic method declarations have ‘<>’ in their argument list. This precedes the method’s return type. This denotes a generic type.
- The parameter section of these methods contains more than one parameter. One of the various types is the type parameter. This type parameter identifies generic type names.
- Not only can the type parameters be used to declare return types of the generic methods, but they also act as placeholders for the argument types that need to be passed to the generic method that you have created. The parameters that fulfil the second part are often termed actual type arguments.
- There is no major change in the declaration type of a generic method. It is just like that of any other method. However, those type parameters can only represent reference. Primitive types like int, char, double, etc., cannot be incorporated here.
Example
public class Demo { public static <E> void printArray ( E[] inputArray) { for (E element : inputArray) { System.out.printf (“%s” , element) ; } System.out.println (); } public static void main (String args []) { Integer [] intArray = {1, 2, 3}; Double [] doubleArray = {1.1, 2.2, 3.3}; printArray (intArray); printArray (doubleArray); } }
OUTPUT
1 ,2, 3
1.1, 2.2, 3.3
0 Comments