You can perform one of the following approaches:
1) Basic, single type:
//One type public static <T> void fill(List <T> list, T val) { for(int i=0; i<list.size(); i++){ list.set(i, val); } }
2) Several types:
// multiple types as parameters public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) { return val1+" "+val2; }
3) The compiler error will be raised below, since "T3 is not included in the list of generic types that are used in the function declaration part.
//Raised compilation error public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) { return 0; }
Right: compiles fine
public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) { return 0; }
Class code example:
package generics.basics; import java.util.ArrayList; import java.util.List; public class GenericMethods { /* Declare the generic type parameter T in this method. After the qualifiers public and static, you put <T> and then followed it by return type, method name, and its parameters. Observe : type of val is 'T' and not '<T>' * */ //One type public static <T> void fill(List <T> list, T val) { for(int i=0; i<list.size(); i++){ list.set(i, val); } } // multiple types as parameters public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) { return val1+" "+val2; } /*// Q: To audience -> will this compile ? * * public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) { return 0; }*/ public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) { return null; } public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(10); list.add(20); System.out.println(list.toString()); fill(list, 100); System.out.println(list.toString()); List<String> Strlist = new ArrayList<>(); Strlist.add("Chirag"); Strlist.add("Nayak"); System.out.println(Strlist.toString()); fill(Strlist, "GOOD BOY"); System.out.println(Strlist.toString()); System.out.println(multipleTypeArgument("Chirag", 100)); System.out.println(multipleTypeArgument(100,"Nayak")); } }
// class definition is completed
Output Example:
[10, 20] [100, 100] [Chirag, Nayak] [GOOD BOY, GOOD BOY] Chirag 100 100 Nayak