Java Generic Methods
by , 02-18-2012 at 03:55 PM (483 Views)
It is also possible and supported to generify methods in Java.
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: This is the code to expalin generic methodspublic static <T> T add(T element, Collection<T> collection){ collection.add(element); return element; }
The given call is also considered legal: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);
Though, its inverse is not considered legal:Java Code:String stringElement = "stringElement"; List<Object> objectList = new ArrayList<Object>(); Object theElement = add(stringElement, objectList);
Java Code:Object objectElement = new Object(); List<String> stringList = new ArrayList<String>(); Object theElement = add(objectElement, stringList);









Email Blog Entry
Size Reduced for Images in PDF &...
05-15-2013, 05:53 PM in Java Software