generic java example
Example 1: java generics
public class Tuple <T> {
public T leftValue;
public T rightValue;
public Tuple(T leftValue, T rightValue){
this.leftValue = leftValue;
this.rightValue = rightValue;
}
public class Program{
public static void main (String args){
Tuple <int> intTuple = new Tuple <int>(5, 500)
Tuple <String> stringTuple = new Tuple <String> ("Hello", "World")
Tuple<Tuple<int>> metaIntTuple = new Tuple <Tuple <int>> (intTuple, new Tuple <int> (456, 0));
}
}
Example 2: 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>