Skip to content

Generic Methods in Java

Ramesh Fadatare edited this page Aug 14, 2018 · 6 revisions

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 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.

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 above method,

 public static void main(String[] args) {
    	String[] str = {"abc","bcd"};
	List<String> list = fromArrayToList(str);
	list.forEach(s -> System.out.println(s));
}

More Examples

Let's create Generic class GenType.

public class GenType<T> {
	private T t;

	public T get() {
		return this.t;
	}

	public void set(T t1) {
		this.t = t1;
	}
}

Let's write generic equals and compare methods to check equality.

public static <T> boolean isEqual(GenType<T> g1, GenType<T> g2){
	return g1.get().equals(g2.get());
}

public static <T extends Comparable<T>> int compare(T t1, T t2){
	return t1.compareTo(t2);
}

The complete example of above generic methods and it's testing code.

public class GenericsMethods {

	//Generics in method
	public static <T> boolean isEqual(GenType<T> g1, GenType<T> g2){
		return g1.get().equals(g2.get());
	}
	
	public static <T extends Comparable<T>> int compare(T t1, T t2){
		return t1.compareTo(t2);
	}
	
	public static void main(String args[]){
		GenType<String> g1 = new GenType<>();
		g1.set("demo");
		
		GenType<String> g2 = new GenType<>();
		g2.set("demo");
		
		boolean isEqual = GenericsMethods.<String>isEqual(g1, g2);
		
		System.out.println(isEqual);
		//above statement can be written simply as
		isEqual = GenericsMethods.isEqual(g1, g2);
		
		System.out.println(isEqual);
		
		System.out.println(GenericsMethods.compare("abc","abc"));
	}
}

Output:

true
true
0
Clone this wiki locally