15

Possible Duplicate:
List versus ArrayList

Difference between

ArrayList al = new ArrayList() 

and

List al = new ArrayList() ?
Community
  • 1
  • 1
Hari kanna
  • 2,461
  • 6
  • 29
  • 43

3 Answers3

10

None, from a creation perspective. Both create an instance of ArrayList.

The difference is that, in you second example, al allows access to all methods implemented on the List interface while, in the first example, al allows access to all (accessible) methods and fields of the ArrayList class.

A practical rule of thumb: use the second pattern. If you need some extra goodies from the ArrayList implementation, then you can always cast:

 List list = new ArrayList();
 // do some adds/removes/... on the list
 ((ArrayList) list).trimToSize();
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
7

Its called programming to interface. Suppose, you need to return this list from your method. So the calling code can have that into a List variable.

public ArrayList getList() {
   ArrayList list = new ArrayList();
    // do something with the list here
   return list;
}

And this,

public List getList() {
   List list = new ArrayList();
    // do something with the list here
   return list;
}

Now for the latter method calling code can have the returned list in List type variable. And you can easily decide later, for some reason, something like this,

public List getList() {
   List list = new LinkedList();
    // do something with the list here
   return list;
}

No change in calling code, whereas with the former you need to change the return type, that would eventually screw up the calling code as well.

Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
7

Paraphrasing my answer to this very similar question about Map vs. HashMap:

There is no difference between the objects. There is a difference in the interface you have to the object. In the first case, the interface is ArrayList, whereas in the second it's List. The underlying object, though, is the same.

The advantage to using List is that you can change the underlying object to be a different kind of list without breaking your contract with any code that's using it. If you declare it as ArrayList, you have to change your contract if you want to change the underlying implementation.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875