List是Collection的一个子接口,是一个有序的集合!
ArrayList是List的一个实现类!、
阅读:
List 和 ArrayList 的区别_蔡小波的博客-CSDN博客_list和arraylist
List<String> list=new ArrayList<String>();
声明为List而不是 ArrayList,使得List这个对象有多种储存形势,不仅仅局限于Arraylist
List list1 = new List(); ------这么定义就是错误的,因为他是一个接口,不能作为一个实例对象,只可以作为一个引用!
List list2 = new ArrayList();//
用List作为对象引用,只能调用ArrayList中与List的公共属性和方法;
ArrayList list3 = new ArrayList();//
而用ArrayList作为对象引用当然就可以调用其中所有方法及属性。
一般情况下如果是用到了第二种定义方法,就说明一定是用到了ArrayList特有的方法或属性。
同时如果List与ArrayList中有相同的属性(如:int i)以及相同的方法(如:void f()),那么当当使用第一种定义方法时,list2.i调用的就是List中的i,list2.f()调用的就是ArrayList中的f().
List和ArrayList区别及用法_hardenyeahyeah的博客-CSDN博客_arraylist list
这个回答也很棒:
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
可以帮助你在大型项目中更改list的方向