This is called programming to interface. This will be helpful in case if you wish to move to some other implementation of List in the future. If you want some methods in ArrayList
then you would need to program to the implementation that is ArrayList a = new ArrayList()
.
The main reason you‘d do this is to decouple your code from a specific implementation of the interface. When you write your code like this:
List list = new ArrayList();
the rest of your code only knows that data is of type List
, which is preferable because it allows you to switch between different implementations of the List
interface with ease.
For instance, say you were writing a fairly large 3rd party library, and say that you decided to implement the core of your library with a LinkedList
. If your library relies heavily on accessing elements in these lists, then eventually you‘ll find that you‘ve made a poor design decision; you‘ll realize that you should have used an ArrayList
(which gives O(1) access time) instead of a LinkedList
(which gives O(n) access time). Assuming you have been programming to an interface, making such a change is easy. You would simply change the instance of List
from,
List list = new LinkedList();
to
List list = new ArrayList();
and you know that this will work because you have written your code to follow the contract provided by the List
interface.
On the other hand, if you had implemented the core of your library using LinkedList list = new LinkedList()
, making such a change wouldn‘t be as easy, as there is no guarantee that the rest of your code doesn‘t make use of methods specific to the LinkedList
class.
All in all, the choice is simply a matter of design... but this kind of design is very important (especially when working on large projects), as it will allow you to make implementation-specific changes later without breaking existing code.
why using List list = new ArrayList() better than Arraylist list?,布布扣,bubuko.com
why using List list = new ArrayList() better than Arraylist list?
原文:http://www.cnblogs.com/leetcode/p/3889224.html