1 min readNov 29, 2017
Variance is really important to pass generics to other functions.
You are wondering how would `List` in java look like if it would not support variance? Just check out arrays :)
Imagine you have the array of integers and you would like to change the first item:
void test() {
Integer[] array = new Integer[10];
replace(array);
}void replace(Number[] numbers) {
numbers[0] = 1.0f;
}
This code would result with Integer array that contains both ints and a float (not good, right?).
Because `List` takes variance into account, trying doing the same thing:
void test() {
List<Integer> integerList = new ArrayList<>();
replace(integerList); // Compiler error}void replace(List<Number> numbers) {
numbers.set(0, 1.0f);
}
results in compiler error.