I have seen two types of declaration of list. Which one is more efficient?
List is an interface while Arraylist is its implementation class.There are many other implementations of list also.
So, their is no underlying implementation difference between both. However, as Arraylist is an implementation class of List it can access all methods the list provides + few methods restricted to arraylist only (defined in Arraylist) like. ensureCapacity .
What i prefer is List<Integer> as its base implementation, and converting list to arraylist / linkedlist is just a function whenever required.
If you use List you will be able to call the methods available in the List interface and you cannot make calls to the new methods available in the ArrayList class. Where as, you are free to use all the methods available in the ArrayList if you use the second one.
The ArrayListclass has only a few methods(i.e clone(), trimToSize(), removeRange() and ensureCapacity()) in addition to the methods available in the List interface.
I would suggest you to use List<Integer> list = new ArrayList<Integer>(); so that if in future you want to change the implementation for any performance constraint, you can do it easily. You need to change at one point only(the instantiation part) List<Integer> list = new LinkedList<Integer>(); Else you will be supposed to change at all the places, wherever, you have used the specific class implementation as method arguments.
Ritesh Verma
As suggested, always try to go with
List<Integer> list = new ArrayList<Integer>();.This Design Pattern principle is called Program to an interface, not an implementation. This holds true for all types of objects instantiation as “Program to an interface” really means “Program to a supertype.”
Read Chapter 1 from Head First Design Patterns to get a better idea.
Checkout more examples here.