generic class and generic method in java code example
Example 1: java generic type method
public <T> List<T> fromArrayToList(T[] a) {
return Arrays.stream(a).collect(Collectors.toList());
}
public static <T, G> List<G> fromArrayToList(T[] a, Function<T, G> mapperFunction) {
return Arrays.stream(a)
.map(mapperFunction)
.collect(Collectors.toList());
}
public <T extends Number> List<T> fromArrayToList(T[] a) {
...
}
<T extends Number & Comparable>
public static void paintAllBuildings(List<? extends Building> buildings) {
...
}
<? super T>
Example 2: java define a generic class that produces
List list = new ArrayList();
list.add("abc");
list.add(new Integer(5));
for(Object obj : list){
String str=(String) obj;
}
Example 3: java define a generic class that produces
List<String> list1 = new ArrayList<String>();
list1.add("abc");
for(String str : list1){
}