• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

DownCast and Generics

 
Anthony Karta
Ranch Hand
Posts: 342
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Barry Gaunt
Ranch Hand
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Anthony Karta
Ranch Hand
Posts: 342
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic