PECS and independent read/write contracts
Definition:
PECS expresses whether a generic argument produces values, consumes values, or needs both operations.
Explanation:
Invariance protects mutable containers.
Illustration image:
Example:
static <T> void appendAll(java.util.List<? extends T> src,
java.util.List<? super T> dst) {
for (T item : src) dst.add(item);
}Expected behavior. A List<Integer> source can append into a List<Number> target.
Internal working:
A source typed ? extends T is safe to read as T; a target typed ? super T is safe to write T into. A wildcard capture helper can maintain a single unknown type where reading and writing the same list is allowed. Keep the bound in the signature only when it expresses a needed constraint.
Interview questions:
Why can a destination List<Number> consume Integer values but not replace List<Integer>?
It can accept Integers, but also accepts other Number subtypes. Mutable generic types are invariant.