Simple question here (I think). Since the statement above declares the shipments variable as a List of type Shipment, but associates it with an instantiation of an ArrayList of type shipment aren't we only allowed to call methods that are associated with the List interface? Aren't there additional methods in ArrayList? How would you cast shipments to an ArrayList, or does that even make sense?
Stephan van Hulst wrote:Yes, if you use the shipments variable without casting, you will only be able to use the methods declared in the List interface.
This is usually the preferred way to do it. Are there methods in ArrayList that you want to use?
No, not in this case. But if I wanted to, how would I do it? Would I have to explicitly declare the variable as a reference to an ArrayList or could I cast the object somehow since I know it's really an ArrayList. I tried casting, but that doesn't seem to work. I just want to make sure I understand what is really happening here, because it doesn't seem to work the same as casting with regular objects.
ArrayList<Shipment> shipments = new ArrayList<Shipment>();
Note that you should always avoid having to cast references. If you *really* need to, here is how you do it:
It would be bad if I were to have a big program that casts List references to an arraylist, because I would then have to go back and change all those casts if I decided to instantiate the reference to another type of list.