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<?>
andMap<?,?>
Array vs Generics
- Array - Covariant: if
Sub
is a subtype ofSuper
, thenSub[]
is a subtype ofSuper[]
. - Generics - Invariant: for
Type1
andType2
,List<Type1>
is neither a subtype nor a supertype ofList<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<>();