This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Why am I permitted to assign a plain ArrayList() to a List<String> ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why am I permitted to assign a plain ArrayList() to a List<String> ?" Watch "Why am I permitted to assign a plain ArrayList() to a List<String> ?" New topic
Author

Why am I permitted to assign a plain ArrayList() to a List<String> ?

Edward Winchester
Ranch Hand

Joined: Sep 16, 2009
Posts: 65
Here's the code that compiles ok but fails at runtime:



I'm from a C++ STL background where the above is simply not allowed because the compiler cannot guarantee that entries in list are of type String. The for() loop failes with a ClassCastException. Just wondering why the Java language is designed to permit the assignment?

Thanks,

PUK
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39062
    
  23
It doesn't compile OK. Surely you will have had warning messages saying "recompile with -Xlint"? If you get that sort of warning, it is a sign that the compiler cannot assure you of something (in this case type safety). If that sort of thing were prohibited any Java1.0 to Java1.4.2 code which is reused in a new application would fail to compile and you would "break" the old code.
Edward Winchester
Ranch Hand

Joined: Sep 16, 2009
Posts: 65
Campbell Ritchie wrote:It doesn't compile OK. Surely you will have had warning messages saying "recompile with -Xlint"? If you get that sort of warning, it is a sign that the compiler cannot assure you of something (in this case type safety). If that sort of thing were prohibited any Java1.0 to Java1.4.2 code which is reused in a new application would fail to compile and you would "break" the old code.


I've been using Netbeans 6.7.1 IDE and just hit F6 to run. There was no compilation errors appearing using this method.

However, clicking "Clean and Build" (i.e. not running) does indeed show me the "Recompile with -Xlint:unchecked for details" message.

Looks like I need to be careful to build separately to ensure I can see the any compilation errors and that I'm not doing something silly.

Many thanks!

Ed
 
 
subject: Why am I permitted to assign a plain ArrayList() to a List<String> ?