Imagine we need a method that takes different types of data and does something. We can create a Generic method for this and reuse it in code.
public <Type Parameter> [Return Type] [MethodName](Argument list…)
{
//Method Body
}
public <T> T methodName(T param) {
// method body
return param;
}
A generic method is declared with type parameters that are specified before the method’s return type.
1. <T>: It is a type parameter section, enclosed in angle brackets that can declare one or more type parameters separated by commas. These parameters act as placeholders for the types that are specified when the method is called.
2. ReturnType T: A method return type can be a generic type parameter.
3. methodName: The name of the method.
4. Argument List(T param): The list of parameters, which can also use the type parameters.
//Define a generic method
public static <T> void callMe(T data) {
System.out.println(data);
}
//Calling the method over different datatypes
callMe("Hi");
callMe(15);
callMe(25.37);
callMe(15L);
callMe(new Car("Ford", "White", 5));
/* output:
Hi
15
25.37
15
generics.Car@45244cd7
*/
A generic print method is useful because it can handle any type of data, from integers, and strings to the custom objects.
This method leverages a single implementation to print different types of data structures like arrays or collections.
public class Printer {
// Generic method to print array elements
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.print(element + " ");
}
System.out.println();
}
public static void main(String[] args) {
Integer[] integerArray = {1, 2, 3, 4, 5};
String[] stringArray = {"Hello", "World", "Generics", "in", "Java"};
System.out.println("Integer Array:");
printArray(integerArray); // Outputs: 1 2 3 4 5
System.out.println("String Array:");
printArray(stringArray); // Outputs: Hello World Generics in Java
}
}
printArray is generic, specified by <T>, which means it can accept an array of any object type.T and prints each element. This is a highly reusable method that works with any type of array.
package genericmethod;
public class ArrayUtils {
public static <T> T getMiddle(T[] array) {
return array[array.length / 2];
}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4, 5};
String[] strArray = {"hello", "world", "generics", "java"};
System.out.println("Middle element (int): "
+getMiddle(intArray));
System.out.println("Middle element (String): "
+getMiddle(strArray));
}
}
Middle element (int): 3
Middle element (String): generics
package genericmethod;
import java.util.Arrays;
public class SwapUtils {
public static <T> void swap(T[] a, int i, int j) {
T temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
String[] strArray = {"one", "two", "three"};
System.out.println("Array before swap: "
+Arrays.toString(strArray));
swap(strArray, 0, 2);
System.out.println("Array after swap: "
+Arrays.toString(strArray));
}
}
Array before swap: [one, two, three]
Array after swap: [three, two, one]
You can combine generic methods with generic classes to enhance flexibility and reusability.
This combination allows you to define methods within a class that can operate on types independent of the class’s generic type, or in conjunction with it.
package genericmethod;
class Pair<K, V> {
private K key;
private V value;
// Constructor
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
// Getters
public K getKey() {
return key;
}
public V getValue() {
return value;
}
// A generic method to compare two pairs' keys or values
public static <T> boolean compare(T part1, T part2) {
return part1.equals(part2);
}
}
public class GenericMethodPair {
public static void main(String[] args) {
Pair<Integer, String> pair1 = new Pair<>(1, "Apple");
Pair<Integer, String> pair2 = new Pair<>(2, "Banana");
// Using the generic method to compare keys (Integer type)
boolean isSameKey = Pair.compare(pair1.getKey(), pair2.getKey());
System.out.println("Keys are the same: " + isSameKey);
// Outputs: Keys are the same: false
// Using the generic method to compare values (String type)
boolean isSameValue = Pair.compare(pair1.getValue(), "Apple");
System.out.println("Values are the same: " + isSameValue);
// Outputs: Values are the same: true
}
}
Keys are the same: false
Values are the same: true
1. Generic Types K and V: The class Pair<K, V> is defined with two generic types, K (key) and V (value). These types are used for the fields and constructors of the class.
2. Generic Method compare: Inside the Pair class, we define a static generic method compare that takes two parameters of the same type T and compares them.
This method is independent of the generic types K and V used by the class, demonstrating how generic methods can introduce their own type parameters.
This method is useful for comparing parts of pairs or any other two values of the same type provided to it.
3. Use Case: The compare method is versatile and can be used to compare any two objects, as long as they are of the same type and their type has a proper .equals() implementation. In the main method, it’s used to compare both the keys and values of Pair instances.
You must be logged in to submit a review.