There are some main benefits of using generics in Java such as :
1-) Strong type-checking
2-) Elimination of casts
3-) Provide a way to develop generic algorithms
Methods can also be designed in a generic fashion in Java, too. Following generic method prints all the elements of an array one-by-one in a for-loop for both wrapper types and custom defined types.
package basics;
public class GenericPrint {
static class Employee
{
String name;
Employee(String pName)
{
name = pName;
}
public String toString() {
return "[Employee Name = "+name+" ]";
}
}
// Generic method
public static <T> void print( T[] inParam )
{
for( T t: inParam )
{
System.out.printf("%s ", t);
}
}
public static void main(String[] args) {
String[] strArr = {"D1","D2","D3","D4"};
print(strArr);
Integer[] intArr = { 1,2,3 };
System.out.println();
print(intArr);
Double[] dArr = { 5.5, 6.6, 7.7 };
System.out.println();
print(dArr);
Employee e1 = new Employee("Emply1");
Employee e2 = new Employee("Emply2");
Employee e3 = new Employee("Emply3");
Employee[] empArr = { e1, e2, e3 };
System.out.println();
print(empArr);
}
}
Create a GenericPrint.java file in your workspace.
When the main method inside the GenericPrint class executed it is going to print :
D1 D2 D3 D4
1 2 3
5.5 6.6 7.7
[Employee Name = Emply1 ] [Employee Name = Emply2 ] [Employee Name = Emply3 ]
No comments:
Post a Comment