• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

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: 59755
188
  • 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
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!