Differences between cast arraylist and cast array in java -
this question has answer here:
- why arrays covariant generics invariant? 8 answers
as jon's answer of post has said, if compiler allows cast (shown below), add other objects later can bad thing program.
arraylist<string> temlist = new arraylist<string>(); arraylist<object> oblist = (arraylist<object>)temlist;//compile error //oblist.add(1); --bad but confuses me why in same situation, array has different behaviours.
string[] strings = new string[10]; object[] temp = (object[])strings;//nothing happens so explain difference here , why java make such design? thanks.
edit: 1 similar question
arrays not 100% objects, mundane objects. arraylist 100% object.
if try assign integer temp array throw arraystoreexception.
so casting arrays fine.
but casting arraylist super object underlying arraylist implementation can hold string (sub class) cause problems during runtime.
thanks generics compiler can identify before happens , can show compiler error. design if not program fail during runtime.
prior java 1.5 generics
list list = new arraylist(); list.add(1); list.add("one"); list.add(100l); was legal coders had lot of instanceof checks. failed check program crashed during runtime.
Comments
Post a Comment