Generic Methods
If any method accepts argument which is supposed to be generic or returns object which is supposed to be generic (like any java collection), then ‘generic method’ can help giving type safe implementation.
Below example shows a method implementation with generic method & without generics. In case of without generic, compiler will give warnings as shown in comments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package ravi.tutorial.java.java7; import java.util.Arrays; import java.util.List; public class GenericMethodTest { public static void main(String[] args) { List<String> list = Arrays.asList("First", "Second", "Third", "Fourth"); /* * Compiler warning = Type safety: The expression of type List needs * unchecked conversion to conform to List<String> */ List<String> firstTwo_NONgeneric = getFirstTwo_NONGenricMethod(list); /* * No compiler warning. Type safe method */ List<String> firstTwo_generic = getFirstTwo_GenricMethod(list); System.out.println("Generic = " + firstTwo_generic); System.out.println("Non Generic = " + firstTwo_NONgeneric); } /* * Generic Method. Syntax = public static <T>**generic type declaration** * List<T>**Return type using generic declared type** * getFirstTwo_GenricMethod(List<T>**Argument type using generic declared * type** list) */ public static <T> List<T> getFirstTwo_GenricMethod(List<T> list) { return Arrays.asList(list.get(0), list.get(1)); } /* * Compiler warning = List is a raw type. References to generic type List<E> * should be parameterized */ public static List getFirstTwo_NONGenricMethod(List list) { return Arrays.asList(list.get(0), list.get(1)); } } |
Output:
1 2 |
Generic = [First, Second] Non Generic = [First, Second] |