generics in java method 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: generics Interface in java
package com.journaldev.generics;
public class GenericsTypeOld {
private Object t;
public Object get() {
return t;
}
public void set(Object t) {
this.t = t;
}
public static void main(String args[]){
GenericsTypeOld type = new GenericsTypeOld();
type.set("Pankaj");
String str = (String) type.get();
}
}