Search code examples
javalistarraylistdeclarationarray-difference

Difference of List and ArrayList in declaration?


Is there a difference between these two? If so, what is it?

List<Integer> x = new ArrayList<Integer>();

and

ArrayList<Integer> x = new ArrayList<Integer>();

Solution

  • The first declaration lets you program to interface. It ensures that later on you can safely replace ArrayList with, say, LinkedList, and the rest of code is going to compile.

    The second declaration lets you program to the class, so you could potentially use methods of ArrayList which do not implement the List interface. For example, you can call ensureCapacity() on the list declared as ArrayList, but not on a list declared as List. Although generally programming to interface should be preferred, there is nothing wrong with doing it if you must call class-specific methods: for example, ability to call ensureCapacity() could save some unnecessary reallocations if you know the new target size of your list.