Java arraylist and polymorphism -
recently find questions java. 1 【a】
arraylist dates = new arraylist(); dates.add(new date()); dates.add(new string()); 【b】
arraylist<date> dates = new arraylist<date>(); dates.add(new date()); dates.add(new string()); do these 2 pieces have compilation errors? guess there should wrong add(new string()) can't make sense clearly.
i cannot find mistake in arraylist, return type of
dates.get()wrong?arraylist dates = new arraylist(); dates.add(new date()); date date = dates.get(0);
what if use (below)?
arraylist<date> dates = new arraylist<date>(); dates.add(new date()); date date = dates.get(0); if student subtype of person, legal?
person p = new student(); student s = new person(); list<person> lp = new arraylist<student>(); list<student> ls = new arraylist<person>();
i struggled these questions 2 days need give me explanation. in advance
for questions 1 , 2, key thing need learn generics.
if write
arraylist dates = new arraylist(); then raw type: compiler doesn't know sort of thing can put arraylist. when write
arraylist<date> dates = new arraylist<date>(); then compiler knows arraylist store instances of date, , can checking you're trying insert , retrieve date values. there both protect , avoid unnecessary gymnastics. second one, find that
dates.add(new string()); won't compile because compiler knows you're trying put of wrong type list. similarly, can write
date date = dates.get(0); because compiler knows what's inside date. first form, wouldn't case: compiler can't enforce type checking, , need cast when got out:
date date = (date) dates.get(0); using raw types can lead errors in program put wrong type in accident , compiler won't able stop you; , makes unnecessarily verbose when retrieve things because have casting yourself. think of generic type parameter (the <date> part) being way of enforcing can go into, , come out of, list. (technically, enforced compiler, , not runtime, that's lesson day... type erasure if you're interested.)
for code:
person p = new student(); student s = new person(); list<person> lp = new arraylist<student>(); list<student> ls = new arraylist<person>(); you hit 1 of annoying aspects of type system. although student subtype of person, doesn't mean arraylist<student> subtype of arraylist<person>. nice if so, it's not. so:
person p = new student(); this line above fine. student person, person reference can hold student instance.
student s = new person(); you can't line above, though. reference s has hold reference student; , person not student. give compile-time error.
list<person> lp = new arraylist<student>(); it nice if 1 worked, doesn't. if want arraylist<student> have have list<student> formal type of lp.
list<student> ls = new arraylist<person>(); this wouldn't work under circumstances, same reason second line failed: person isn't student, , list<student> can't expected hold isn't student.
Comments
Post a Comment