Java Generic - vinhtbkit/bkit-kb GitHub Wiki

Why generics

  • Code reuse
  • Type safety
  • Better performance

Generic Syntax:

Class

class GenericClass<T > {
 T element;
}

Method

<T> void genericMethod(List<T> list) {
    
  }

Multiple Generic types

<T1, T2> void genericMethod(T1 a, T2 b) {

}

Wildcard

Unbounded wildcard

Represent an unknown type

void test(List<?> lst) {
  lst.foreach(e -> System.out.println(e));
}

Upper bounded wildcard

interface Animal {
  void run();
}

void test(List<? extends Animal> lst) {
  lst.foreach(a -> a.run()));
}

Upper bounded without wildcard

  static <T extends Comparable<Object>> T max(T a, T b) {
    return a.compareTo(b) > 0 ? a : b;
  }

Lower bounded wildcard

interface Person{}
interface Employee extends Person {}

  public static void save(List<? super Person> list) {
    // save
    list.forEach(e -> {
      // save 
    });
  }
  
save(objectList); // valid
save(personList); // valid
save(employeeList); // invalid

PECS

  • Producer Extends, Consumer Super
  • If you need to retrieve (produce) items from a structure, use <? extends T>
  • If you need to insert (consume) items into a structure, use <? super T>

Heap Pollution

  static <T> void doSomething(T... args) {
    Object[] objectArray = args;     // Valid
    objectArray[0] = "I don't fit in"; // ArrayStoreException
  }
⚠️ **GitHub.com Fallback** ⚠️