logo

Java - Generics

  • Enforce type constraints only at compile time and discard type info at runtime.
  • cannot use instanceof
  • non-reifiable type: List<String>, runtime representation contains less info than compile-time representation.
  • reifiable: List<?> and Map<?,?>

Array vs Generics

  • Array - Covariant: if Sub is a subtype of Super, then Sub[] is a subtype of Super[].
  • Generics - Invariant: for Type1 and Type2, List<Type1> is neither a subtype nor a supertype of List<Type2>.

Get Data

protected <T> T getData(String varName, Class<T> c) {
    if (!inputVarMap.containsKey(varName)) {
        return null;
    }
    Object o = inputVarMap.get(varName);
    try {
        return c.cast(o);
    } catch (ClassCastException e) {
        e.printStackTrace();
        return null;
    }
}

How to use:

cpId = getData("cpId", String.class);

Diamond Operator

Since Java 7.

Type Inference for Generic Instance Creation

Map<String, List<String>> myMap = new HashMap<>();