Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Help me understand Collection polymorphism  RSS feed

 
Jonathan Haybok
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
List<Shipment> shipments = new ArrayList<Shipment>();

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
Saloon Keeper
Posts: 7797
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Jonathan Haybok
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stephan van Hulst
Saloon Keeper
Posts: 7797
142
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you really want to use ArrayList methods, and you know it's going to be an ArrayList, you should probably use an ArrayList variable:
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:
(ArrayList<Shipment>) shipments;
 
Jonathan Haybok
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for clearing that up. I had to think about it for a little bit, but I guess the whole point is to choose the variable type that fits your needs and provides the most flexibility based on those needs.

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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!