Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use interface or type for variable definition in java?

Tags:

java

ArrayList aList = new ArrayList();

List aList = new ArrayList();

What's the difference between these two and which is better to use and why?

like image 791
John Avatar asked Sep 22 '10 11:09

John


1 Answers

List is an Interface, whereas ArrayList is an implementation of that interface.

The second is better because it means you can change your ArrayList for another implementation of List later without needing to change the rest of your application. You may want to do this for performance reasons, or because of other aspects of the behaviour of the List implementation that you have chosen/will choose.

like image 120
Rich Avatar answered Oct 16 '22 21:10

Rich