File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes DownCast and Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "DownCast and Generics" Watch "DownCast and Generics" New topic
Author

DownCast and Generics

Anthony Karta
Ranch Hand

Joined: Aug 09, 2004
Posts: 342
from javaBeat mock.
at ## why/how compiler or JVM allows b (refer to Car previously) casting to ArrayList of type Bus?? Car and Bus are sibling, not parent-child relationship.



SCJP 5
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
It's because of this line: "ArrayList b = a;".
Notice that on the next line: "ArrayList<Bus> c = (ArrayList<Bus> )b;" you get an unchecked warning. That's because the compiler no longer knows the exact type of the objects in the array b. It's (to the compiler) just an array of objects. It allows the cast but emits the nonchecked warning so you are aware that it could cause a runtime ClassCastException later. That's would happen if the for loop was changed to:


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Anthony Karta
Ranch Hand

Joined: Aug 09, 2004
Posts: 342
Thanks Barry, that's really helpful. I'm taking the exam in the next 2 days, but still not sure if I'm really well prepared or just give it ago. scored around 50-80% (just couple of times though) on various mock exams.

Originally posted by Barry Gaunt:
It's because of this line: "ArrayList b = a;"


just wonder and I think this will be useful, why compiler does Not give us a warning when we assign typed collection to "plain" collection?
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
The code: does not generate a warning because it is 100% OK to do it. Variable b only needs an ArrayList of some kind of objects assigned to it. They do not even have to be the same type, but here we are in fact assigning an ArrayList of objects that are all the same - Cars. So at this point there is nothing for the compiler to complain about.
[ January 22, 2007: Message edited by: Barry Gaunt ]
 
Don't get me started about those stupid light bulbs.
 
subject: DownCast and Generics
 
Similar Threads
Generics Doubt (Casting)
generic
Warnings during Generic assignments
mock test for generics & collections
About generics..