Sobes.tech
Senior

Tell us about the features of upper and lower bound constraints in wildcards (PECS principle, covariance/contravariance)

sobes.tech AI

Answer from AI

In Java, wildcard restrictions allow managing types in generics using upper (extends) and lower (super) bounds, related to the PECS principle (Producer Extends, Consumer Super).

  • ? extends T (covariance) — used when the object acts as a source (producer) of data of type T or its subtypes. It allows reading data but not adding (except null).
  • ? super T (contravariance) — used when the object acts as a consumer of data of type T or its supertypes. It allows adding objects of type T, but reading returns objects of type Object or a supertype.

Example:

List<? extends Number> numbers = new ArrayList<Integer>();
Number num = numbers.get(0); // Can read
// numbers.add(10); // Compilation error

List<? super Integer> integers = new ArrayList<Number>();
integers.add(10); // Can add
Object obj = integers.get(0); // Reading returns Object

Thus, the upper bound limits types for reading (covariance), and the lower bound for writing (contravariance). This helps avoid type errors and increases code flexibility.