PDA

View Full Version : [Java] Compilation Warnings


Pulse
14-Dec-2004, 23:49
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 :)

bink
15-Dec-2004, 00:27
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.

Sparky
23-Dec-2004, 15:07
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

Pulse
23-Dec-2004, 19:36
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

Pulse
14-Jan-2005, 22:21
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 :/

ezt
15-Jan-2005, 01:07
Yeah, eclipse doesn't properly support java5 yet. Try 3.1M4 - it ought to be "kinda" stable :P

Pulse
15-Jan-2005, 20:22
Unstableness here I come :P