• Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Marshal
Posts: 57276
175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
We noticed he had no friends. So we gave him this tiny ad:
The WEB SERVICES and JAX-RS Course
https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!