View RSS Feed

Advanced Java

Java Generic Methods

Rate this Entry
by , 02-18-2012 at 03:55 PM (770 Views)
It is also possible and supported to generify methods in Java.

Java Code: This is the code to expalin generic methods
public static <T> T add(T element, Collection<T> collection){
    collection.add(element);
    return element;
}
A type T is being specified by this method. It is used as generic type of collection as well as for element parameter type.

Java Code:
String stringElement = "stringElement";
List<String> stringList = new ArrayList<String>();
String theElement = add(stringElement, stringList);    
Integer integerElement = new Integer(123);
List<Integer> integerList = new ArrayList<Integer>();
Integer theElement = add(integerElement, integerList);
The given call is also considered legal:

Java Code:
String stringElement = "stringElement";
List<Object> objectList = new ArrayList<Object>();
Object theElement = add(stringElement, objectList);
Though, its inverse is not considered legal:

Java Code:
Object objectElement = new Object();
List<String> stringList = new ArrayList<String>();
Object theElement = add(objectElement, stringList);

Submit "Java Generic Methods" to Facebook Submit "Java Generic Methods" to Digg Submit "Java Generic Methods" to del.icio.us Submit "Java Generic Methods" to StumbleUpon Submit "Java Generic Methods" to Google

Categories
Generics

Comments