/** A quick example of the covariance and the use of the ? * in generic types in Java. * As said in class, you cannot change the contents of the * ArrayList in the add2Ai method, however, you can change the * contents of the items contained therein, so long as the * contents are a part of A * * The actual actions taken by the add2Ai are irrelevant. What * is important is the weird rather than just . * * @author gtowell * Created Oct 6, 2021 */ import java.util.ArrayList; public class Cov { private abstract class A { int ai; public void add2Ai(int amt, ArrayList arrL) { for (A aa : arrL) { aa.ai += amt; } } } private class B extends A { int bi; public void dooB() { ArrayList arrB = new ArrayList<>(); for (int i = 0; i < 5; i++) { arrB.add(new B()); arrB.get(i).bi = i; arrB.get(i).ai = i - 5; } System.out.println("Before " + arrB); arrB.get(0).add2Ai(4, arrB); System.out.println("After " + arrB); } public String toString() { return "<>"; } } private class C extends A { int ci; public void dooC() { ArrayList arrC = new ArrayList<>(); for (int i = 0; i < 5; i++) { arrC.add(new C()); arrC.get(i).ci = i * i * i; arrC.get(i).ai = i - 5; } System.out.println("Before " + arrC); arrC.get(0).add2Ai(4, arrC); System.out.println("After " + arrC); } public String toString() { return "<>"; } } public static void main(String[] args) { new Cov().doo(); } public void doo() { Cov cov = new Cov(); B bi = new B(); C ci = new C(); bi.dooB(); ci.dooC(); } }