Friday, 31 May 2013

List and ArrayList Declaration

What is the difference between these two declarations:

Declaration 1 : ArrayList<String> arrayList = new ArrayList<String>();Declaration 2 : List<String> arrayList = new ArrayList<String>();

List is an interface. ArrayList, LinkedList.. etc are classes which implement list. When you are using List Interface,you have to iterate elements using List-Iterator and can move forward and backward,in the List where as in ArrayList Iterate using Iterator and its elements can be accessed unidirectional way.

Let's see in Brief Explanation:
List<String> arrayList = new ArrayList<String>();
Is generic where you want to hide implementation details while returning it to client, at later point of time you may change implementation from ArrayList to LinkedList transparently.
This mechanism is useful in cases where you design libraries etc., which may change their implementation details at some point of time with minimal changes on client side.
ArrayList<String> arrayList = new ArrayList<String>();
This mandates you always need to return ArrayList. At some point of time if you would like to change implementation details to LinkedList, there should be changes on client side also to useLinkedList instead of ArrayList.

No comments:

Post a Comment