list and arraylist

(1) List<?> myList = new ArrayList<?>(); (2) ArrayList<?> myList = new ArrayList<?>();

 

Almost always the first one is preferred over the second one. The first has the advantage that the implementation of the List can change (to a LinkedList for example), without affecting the rest of the code. This is will be difficult to do with an ArrayList, not only because you will need to change ArrayList to LinkedList everywhere, but also because you may have used ArrayList specific methods.

  • List is an interface; ArrayList is a class that implements the List interface.

Interfaces define the method signatures that are required, but say nothing about how they are implemented.

Classes that implement an interface promise to provide public implementations of methods with the identical signatures declared by the interface.

  • When you define your list as:
List myList = new ArrayList();

you can only call methods and reference members that belong to List class. If you define it as:

ArrayList myList = new ArrayList();

you’ll be able to invoke ArrayList specific methods and use ArrayList specific members in addition to those inherited from List.

Nevertheless, when you call a method of a List class in the first example, which was overridden in ArrayList, then method from ArrayList will be called not the one in the List.

That’s called polymorphism.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s