Class Generic

  • Note: Generic types cannot be a primitive type
class Test<T>
{
    // An object of type T is declared
    T obj;
    Test(T obj) {  this.obj = obj;  }  // constructor
    public T getObject()  { return this.obj; }
}
  • Example: Pagination
Page<Employee> pagedData;

Method Generics

  • Before return type we define type parameters inside diamond operator (even if we are returning void)
static <T> void genericDisplay (T element)
{
	System.out.println(element.getClass().getName() +
					   " = " + element);
}
  • If using multiple generic types, then type parameter is separated by comma
  • In the below example: <T, G>
public static <T, G> List<G> fromArrayToList(T[] a, Function<T, G> mapperFunction) {
    return Arrays.stream(a)
      .map(mapperFunction)
      .collect(Collectors.toList());
}

Bounded Type Parameters

  • Subclass
<T extends SuperClass>
  • There is no superclass?
  • Multiple Bounds:
    • T is subtype of B1, B2, B3
<T extends B1 & B2 & B3>

Wildcards

  • Using unknown type ?
static <? extends Building> void genericDisplay (<? extends Building> element) # subclasses of Building class
static <? super Building> void genericDisplay (<? super Building> element) # superclasses of Building class

Varargs

public class Test {
    static void printSomething(String... elements) {
        for (var element:elements) {
            System.out.println(element);
        }
    }
 
    public static void main(String[] args) {
        // printSomething() can take comma separated strings or list of String in its input
        printSomething("Hello", "World");
        // is same as
        printSomething(new String[] {"Hello", "World"});
    }
}

Type Erasure

https://hyperskill.org/knowledge-map/1273?track=35

Reification