/** * Arrays are covariant in Java. Hence, you can pass * Integer[] into changeN and printArr methods. But you cannot pass * Number[] into changeI. * Likewise you can assign a Number[] to a var of type integer[] * but not the opposite * * @author: gtowell * created: July 2022 */ public class ArraCov { /** * Set the values in an Integer[]. * NOTE: side effects abound (as per functional programming) * Note use of autoboxing * @param iArr the array to be set */ private void changeI(Integer[] iArr) { for (int i = 0; i < iArr.length; i++) iArr[i] = i; } /** * Set the values in a Number[] * Because of covariance, can pass an Integer array in to this * function. But then I can try to put a non-integer into the * integer array ... BAD * @param nArr the array to be set */ private void changeN(Number[] nArr) { for (int i = 0; i < nArr.length; i++) nArr[i] = i+13.2; } /** * Print the contents of the passed array * @param nArr the passed array */ public void printArr(Number[] nArr) { for (int i = 0; i < nArr.length; i++) System.out.println(i + " " + nArr[i]); } /** * Testing function for covariant arrays */ public void test() { Number[] nArr = new Number[5]; Integer[] iArr = new Integer[5]; nArr = iArr; for (int i = 0; i < nArr.length; i++) { nArr[i] = Double.valueOf(i + 10.5); iArr[i] = Integer.valueOf(i); } printArr(nArr); printArr(iArr); //changeI(nArr); // will not compile changeN(nArr); changeN(iArr); printArr(nArr); nArr = iArr; //iArr = nArr; // will not compile } /** * Testing function for variant types */ private void test0() { Number nl; Integer ii = Integer.valueOf(3); nl = ii; nl = Double.valueOf(3.5); System.out.println(nl + " " + ii); } public static void main(String[] args) { //new ArraCov().test0(); new ArraCov().test(); } }