Java中List和ArrayList的区别

List是一个接口,而ArrayList是一个类。 

public interface List<E> extends Collection<E> {
    int size();
    boolean isEmpty();
    boolean contains(Object o);
    Iterator<E> iterator();
    Object[] toArray();
    <T> T[] toArray(T[] a);
    boolean add(E e);  
    boolean remove(Object o);
    boolean containsAll(Collection<?> c);
    boolean addAll(Collection<? extends E> c);
    boolean addAll(int index, Collection<? extends E> c);
    boolean removeAll(Collection<?> c);
    boolean retainAll(Collection<?> c);
    ...
}
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private int size;
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
	...
}
ArrayList继承并实现了List。 
因为List是一个接口,所以不能被创建实例,但是可以创建引用变量,如:List<Integer> list = null;

List<Integer> list = new List<>();则是错误的用法。

但是我们可以这样使用:

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

为什么要用 List<Integer> list = new ArrayList<>(); ,而不用 ArrayList<Integer> list = new ArrayList<>();呢? 
问题就在于List有多个实现类,现在你用的是ArrayList,也许哪一天你需要换成其它的实现类,如 LinkedList或者Vector等等,这时你只要改变这一行就行了: 
List<Integer> list = new LinkedList<>(); 其它使用了list地方的代码根本不需要改动。 


Keep it simple!
作者:N3verL4nd
知识共享,欢迎转载。
原文地址:https://www.cnblogs.com/lgh1992314/p/6616256.html