What makes it possible to add a Pair<String, String> when I'm only extending the class Number ? Does't this violate the expectation that an array should only hold elements of the same type ?
public class test {
public static void main(String[] args) {
Pair<? extends Number, ? extends Number>[] arr = new Pair[2];
m1(arr);
arr[1] = new Pair<Integer, Integer>(1, 1);
System.out.println(arr[0].x);
System.out.println(arr.getClass().getComponentType());
}
static void m1(Object[] arr) {
arr[0] = new Pair<String, String>("test","test");
}
}
class Pair<T, E> {
public T x;
public E y;
public Pair(T x, E y) {
this.x = x;
this.y = y;
}
}
We have the following situation: inheritance in Java is on multiple levels, not just on 2 levels.
Relations:
So an
IntegerIS aNumber, just with some additional functionality. Same forDouble. If you tell the array (define, declare) to holdNumbers, by writing eitherList<Number> listorList(? extends Number) list(soNumberor any subclass thereof), then you can add anyNumber.If you created an array of
Numbers like this:arr[0] = new Double(2.0);(initialize and assign) then the new value is aDouble, butDoubleis aNumber, so the new value also is still aNumber. So this is totally valid.In your case, you create an array of
Pairs ofNumbers, making the whole thing a little more convoluted, but the basic principle remains the same: The "declared" type is stillNumberfor all of them, but the assigned value isDoubleorInteger(which are still alsoNumbers). You could still sort this out later byinstanceOfchecks to see what different subtypes the values are, if need be.