I wonder why Java compiler doesn’t trust in this line of code :
List<Car> l = new ArrayList();
and expects to have a typed ArrayList :
List<Car> l = new ArrayList<Car>();
Indeed, compiler indicates an unchecked assignment with the first case.
Why doesn’t compiler see that this ArrayList() has just been created and so it’s impossible to find already in it some objects other than ‘Car’?
This warning would make sense if the untyped ArrayList was created before but doesn’t in this case …
Indeed, since List is typed as ‘Car’, all futures “l.add(‘object’)” will be allowed only if ‘object’ is a ‘Car’. => So, according to me, no surprise could happen.
Am I wrong ?
Thanks
The simple answer is “Because it is not allowed to.”
The compiler has to implement the Java Language Specification. If some compiler writer goes and adds a bunch of smarts to the compiler to allow things that “everyone” knows are safe, then what he’s actually done is to introduce a portability problem. Code compiled and tested with this compiler will give compilation errors when compiled with a dumb (or more accurately, strictly conformant) Java compiler.
So why doesn’t the JLS allow this? I can think of a couple of possible explanations:
And then there is the associated question of whether a compiler could implement such a check. I’m not qualified to answer that … but I know enough about the problem to realize that it is not necessarily as simple to solve as one might imagine.