The developer can create generic method that can accept any type of argument. Following is an example to print array of elements.
GenericMethod.java
[java]
public class GenericMethod {
public static void printArray(E[] elements) {
for ( E element : elements){
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] ) {
Integer[] intArray = { 100, 200, 300 };
Character[] charArray = { 'S', 'P', 'L', 'E', 'S','S','O','O','N','S' };
System.out.println( "Printing Integer Array" );
printArray( intArray );
System.out.println( "Printing Character Array" );
printArray( charArray );
}
}
[/java]
Here the developer used
E to denote the element.
[java]public static void printArray(E[] elements) {
for ( E element : elements)}[/java]
Output
When compile the code following is the result will be displayed. Where first integer array, second character array will be displayed.
[java]Printing Integer Array
100
200
300
Printing Character Array
S
P
L
E
S
S
O
O
N
S
[/java]
Difference between generics and collections
1)Its not a class or interface,so its unfair to compare it with interfaces,comparisons are done between two things that share some common properties.
2)is actually a concept with which you can restrict the type of element you want to add into collection.
There is not compile time check for the type of elements being added into collection.
3)While accessing the elements you need to write many typecasting code with if-else condition to process the data.This is a very big problem with java2 collections.
4)To resolve this problem Java vendor has added the concept of Generics in Java 5.
click here .