This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Upcasting is always safe - the compiler will tell you if it's not. Something as simple as:
creates a real ArrayList but references it as a List. This is actually a pretty good idea as long as none of the later code needs methods that are on ArrayList but not on List.
A down cast might or might not work. At runtime it might throw an exception.
The parameter passed to this method must be a List. It might or might not be an ArrayList. If I'm real sure it's an ArrayList I can try to cast it to ArrayList as shown, but I'd be smart to remember it might not work.
Casting is very common with collections. If I know my Map only contains Widgets, I can write this:
But I run the risk of an exception if some other type of object gets into the list!
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi