java

Assigning ArrayList to List


Is there any Difference between two lines in the following

 ArrayList<String> arrName =  new ArrayList<String>();
 List<String>      arrName =  new ArrayList<String>();

Solution

  • Almost always the second one is preferred over the first one. The second 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.