java - purpose of checkedList method in Collections class -
the api says "returns dynamically typesafe view of specified collection" still need when generics can detect @ compile time if suspicious being inserted collection.
the doc says "the generics mechanism in language provides compile-time (static) type checking, possible defeat mechanism unchecked casts"
but won't work
list<integer> list = new arraylist<integer>(); object o = new float(1.2); integer = (integer)o; // line3 list.add(i);
but 1 wud fail @ run time classcastexception
being thrown @ line3 because o holds float
, can't convert integer
. , wondering how 1 go around static compile-time generic checking justify existence of checkedlist method
this can done not using generics, done if use library built version of java doesn't have generics.
the following code example of how generics:
list<integer> list = new arraylist<integer>(); list unsafelist = list; // cast list not using generics object o = new float(1.2); unsafelist.add(o); // list contains non integer object.
this generate several warnings, can of course ignore if want.
Comments
Post a Comment