Sobes.tech
Junior — Middle

Mis vahe on märksõnadel extends ja super Java generics kasutamisel?

sobes.tech AI

Vastus AI-lt

In Java, when working with generics, the keywords extends and super are used to restrict types and influence covariance and contravariance.

  • ? extends T — upper bound (covariance). Allows using type T or any of its subclasses. This means you can read objects of type T from the collection, but cannot safely add objects to such a collection (except null).

  • ? super T — lower bound (contravariance). Allows using type T or any of its superclasses. This means you can add objects of type T to the collection, but when reading, you only get objects of type Object or more general types.

Example:

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

List<? super Integer> listSuper = new ArrayList<Number>();
listSuper.add(10); // Can add Integer
Object obj = listSuper.get(0); // When reading, type is Object

Thus, extends is used when you need to read data from the structure, and super when you need to write data.