Friday 15 July 2011

Java generics unchecked casts - wildcard bounds -



Java generics unchecked casts - wildcard bounds -

i'm trying understand generics, block @ wildcard bounds , casts. instance:

list<? extends number> l = new arraylist<>(); list<positiveinteger> p = new arraylist<positiveinteger>(); p.add(new positiveinteger(10)); l = p; negativeinteger ni = (negativeinteger) l.get(0);// runtime java.lang.classcastexception: system.out.println(ni);

negativenumber , positivenumber both extend number. question why there no warning @ compile-time when casting element list negativenumber ? there way prevent type of exception ?

well, same thing happen if you'll do:

object a; integer b = new integer(5); a=b double c = (double)a;

classcastexception happend because trying convert class class isn't parent/child class

as question preventing it:

the compiler don't know in l in run time. can utilize list<positiveinteger> instead of wildcard tell compiler going in l. if have utilize list<? extends number> can create method tries cast object, way can tell if object list<positiveinteger> or list<negativeinteger> here:

if(l instanceof list<negativeinteger>){ //do }

so if alter code accordingly:

list<? extends number> l = new arraylist<>(); list<positiveinteger> p = new arraylist<positiveinteger>(); p.add(new positiveinteger(10)); l = p; object ni = l.get(0); if(ni instanceof negativeinteger){ negativeinteger tmp = (negativeinteger)ni; system.out.println(ni); }

java generics warnings

No comments:

Post a Comment