I was messing around with some Java code in my terminal, when I came across the following problem. Let me preface it.
Check out the following code:
Integer x = new Integer(5);
Number y = x
Here, we are simply declaring an Integer object, and then creating a reference to it with the use of superclass Number. This works fine and dandy, because the Integer is a Number.
Thus, it would seem intuitive that the following code should work too:
ArrayList<Integer> x = new ArrayList<>();
x.add(6);
ArrayList<Number> y;
y = x;
But this code gives us an error stating incompatible types: ArrayList<Integer> cannot be converted to ArrayList<Number> y = x;
Now I am confused. As I understood generics, I thought we were declaring an ArrayList x
that is being enforced to hold only objects of the Integer
class at both compile time and run time. And since Integer
is a Number
, then it makes sense that we should be able to treat all Integers as Numbers. But this thinking doesn't line up: What am I doing wrong here?