Generic Methods in Java

In the previous post, we have learned the Java Generics Basics. In this post, we will learn how to create generic methods with lots of examples.
Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.

The Syntax for Defining Generic Method

<type-Parameters> return_type method_name(parameter list)
{
  // ..
}
The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type.

Generic Methods Examples

The Util class includes a generic method, compare, which compares two Pair objects:
public class Util {
    public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
        return p1.getKey().equals(p2.getKey()) &&
               p1.getValue().equals(p2.getValue());
    }
}
public class Pair<K, V> {

    private K key;
    private V value;

    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public void setKey(K key) { this.key = key; }
    public void setValue(V value) { this.value = value; }
    public K getKey()   { return key; }
    public V getValue() { return value; }
}
The complete syntax for invoking this method would be:
Pair<Integer, String> p1 = new Pair<>(1, "apple");
Pair<Integer, String> p2 = new Pair<>(2, "pear");
boolean same = Util.<Integer, String>compare(p1, p2);
The type has been explicitly provided, as shown in bold. Generally, this can be left out and the compiler will infer the type that is needed:
Pair<Integer, String> p1 = new Pair<>(1, "apple");
Pair<Integer, String> p2 = new Pair<>(2, "pear");
boolean same = Util.compare(p1, p2);

Convert Array to ArrayList Generic Method

public static <T> List<T> fromArrayToList(T[] a) {
      return Arrays.stream(a).collect(Collectors.toList());
}
Test the above method,
 public static void main(String[] args) {
     String[] str = {"abc","bcd"};
 List<String> list = fromArrayToList(str);
 list.forEach(s -> System.out.println(s));
}

Generic Method to Search an Element in an Array

    /**
     * if array elements are sorted then use java.util.Arrays.sort for better
     * performance
     * 
     * 
     * @param array
     * @param elm
     * @return will return -1 if elem not found else will return indx of elem
     * 
     */
    public static final <T> int search(T[] array, T v) {
        T e = null;
        for (int i = 0; i < array.length; i++) {
            e = array[i];
            if (e == v || v != null && v.equals(e)) {
                return i;
            }
        }

        return -1;
    }

Generic Method to Check an Element Contains in an Array

public static final <T> boolean contains(final T[] array, final T v) {
        for (final T e : array)
            if (e == v || v != null && v.equals(e))
                return true;

        return false;
}

Comments