View Full Version : [Java] Compilation Warnings
When I cast something coming out of an ArrayList will java always throw a warning because it is unsafe in the sense that there is no garuntee that what comes out of the ArrayList object is definately the type I am casting it as?
For instance:
nameOfClass objClass = (nameOfClass) objArrayList.get(i);
An array list is just a collection of objects, dont all have to be the same type.
Thanks for any advice :)
Yes it will always give a warning. There's no way for the compiler to know what objects will be in that ArrayList, so if you try and cast it to something it isn't at runtime, you'll end up with a ClassCastException.
Warning don't stop you compiling though. You can do javac -nowarn which will suppress them if they're too annoying, or if you're using Java 1.5 I think there's some new options to just suppress just these casting exceptions.
In Java 1.5, there are Generics:
e.g.
Vector<String> myVectorOfStrings = new Vector<String>();
String a = new String("woo");
String b = new String("moo");
myVectorOfStrings.add(a);
myVectorOfStrings.add(b);
String c = myVectorOfStrings.get(0); // Ahah - no cast required.
phantom
23-Dec-2004, 15:55
the C++ 1998 standard called, they'd like the templates backs :P
The generics thing is quite handy :).
phantom
23-Dec-2004, 21:34
yep, template/generic program is pretty cool when you get into it :D
Hhhmm, If I can get into it! ;). Seems that Eclipse doesnt damn well support them :(. Looks like I need a later build though some are unstable :/
Yeah, eclipse doesn't properly support java5 yet. Try 3.1M4 - it ought to be "kinda" stable :P
Unstableness here I come :P
vBulletin® v3.7.0 Release Candidate 3, Copyright ©2000-2009, Jelsoft Enterprises Ltd.