Generics 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 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 3: generic argument java
static void fromArrayToCollection(Object[] a, Collection<?> c) {
for (Object o : a) {
c.add(o);
}
}
Example 4: java generics type
Java Generic Type Naming convention helps us understanding code easily and having a naming convention is one of the best practices of Java programming language. So generics also comes with its own naming conventions. Usually, type parameter names are single, uppercase letters to make it easily distinguishable from java variables. The most commonly used type parameter names are:
E – Element (used extensively by the Java Collections Framework, for example ArrayList, Set etc.)
K – Key (Used in Map)
N – Number
T – Type
V – Value (Used in Map)
S,U,V etc. – 2nd, 3rd, 4th types
Example 5: generics Interface in java
public static <T extends Comparable<T>> int compare(T t1, T t2){
return t1.compareTo(t2);
}
Example 6: generics Interface in java
package com.journaldev.generics;
public class GenericsInheritance {
public static void main(String[] args) {
String str = "abc";
Object obj = new Object();
obj=str;
MyClass<String> myClass1 = new MyClass<String>();
MyClass<Object> myClass2 = new MyClass<Object>();
obj = myClass1;
}
public static class MyClass<T>{}
}