Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList or List declaration in Java

Tags:

java

arraylist

What is the difference between these two declarations?

Declaration 1:

ArrayList<String> arrayList = new ArrayList<String>(); 

Declaration 2:

List<String> arrayList = new ArrayList<String>(); 
like image 690
Adil Avatar asked Sep 07 '12 15:09

Adil


People also ask

Why do we declare ArrayList as List?

List is an interface, and ArrayList is an implementing class. It's almost always preferable to code against the interface and not the implementation. This way, if you need to change the implementation later, it won't break consumers who code against the interface.

What's the difference between List and ArrayList in Java?

List and ArrayList are the members of Collection framework. List is a collection of elements in a sequence where each element is an object and elements are accessed by there position (index). ArrayList creates a dynamic array of objects that increases or reduces in size whenever required.


1 Answers

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 use LinkedList instead of ArrayList.

like image 192
kosa Avatar answered Sep 24 '22 18:09

kosa