zoukankan      html  css  js  c++  java
  • 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
    知识共享,欢迎转载。
  • 相关阅读:
    win7下的nginx小demo
    破解navicat
    MVC下用C#实现Excel导出
    使用IE10登录,URL出现SessionId的解决办法
    C#错误:The Controls collection cannot be modified
    更改数据库排序规则
    windows server 2008 r2电脑历史操作记录
    jquery easyui无法绑定下拉框内容
    Jquery实现自动提示下拉框
    CLSID {91493441-5A91-11CF-8700-00AA0060263B}错误
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/6616257.html
Copyright © 2011-2022 走看看