Member-only story

Java Generic Functions

Sukhvinder Singh
1 min readMar 10, 2023

--

Java generic functions are functions that are defined with type parameters, allowing them to work with different types of data. These type parameters are specified within angle brackets (< >) before the return type of the function.

Here’s an example of a generic function that takes in an array of any type and returns the minimum value:

public static <T extends Comparable<T>> T getMin(T[] array) {
T min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i].compareTo(min) < 0) {
min = array[i];
}
}
return min;
}

In this example, the type parameter <T> is used to specify that the function can work with any type that extends the Comparable interface. The Comparable interface ensures that the type parameter can be compared to other instances of the same type.

With this function, you can pass in an array of any type that extends Comparable, and it will return the minimum value of that array.

Integer[] intArray = { 4, 3, 7, 6, 1 };
double[] doubleArray = { 7.5, 1.25, 0.25, 1.5 };
String[] stringArray = { "cat", "dog", "rabbit" };
System.out.println(getMin(intArray));     // Output: 1
System.out.println(getMin(doubleArray)); // Output: 0.25
System.out.println(getMin(stringArray)); // Output: "cat"

Using generic functions can make your code more flexible and reusable, as they allow you to write code that can work with a variety of data types.

--

--

Sukhvinder Singh
Sukhvinder Singh

Written by Sukhvinder Singh

Software Developer, Software Architect, Inventor, Quant

No responses yet