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, 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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With