2

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?

Dr. Java
  • 63
  • 6
  • 4
    Ooh, wait I just realized one reason why the compiler may not have liked this... with my line of thinking, we can now add ```Numbers``` to the ```Integer``` ArrayList during compile time. – Dr. Java Nov 17 '20 at 18:08
  • 4
    Correct. You just identified that `ArrayList` is invariant and then figured out the chief problem that arises if we try to pretend that it's not invariant. – Silvio Mayolo Nov 17 '20 at 18:10

0 Answers0