This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan 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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 38087
    
  22
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> ?
 
Similar Threads
Using JCheckBox as CellRenderer in JList
Question on Semaphores
Doubt in Generics...
generics code mixed with legacy collection
ClassCastException