• 第十二章 ArrayList&LinkedList源码解析


    一、对于ArrayList需要掌握的七点内容

    • ArrayList的创建:即构造器
    • 往ArrayList中添加对象:即add(E)方法
    • 获取ArrayList中的单个对象:即get(int index)方法
    • 删除ArrayList中的对象:即remove(E)方法
    • 遍历ArrayList中的对象:即iterator,在实际中更常用的是增强型的for循环去做遍历
    • 判断对象是否存在于ArrayList中:contain(E)
    • ArrayList中对象的排序:主要取决于所采取的排序算法(以后讲)

    二、源码分析

    2.1、ArrayList的创建(常见的两种方式)

            List<String> strList = new ArrayList<String>();
            List<String> strList2 = new ArrayList<String>(2);

    ArrayList源代码:

    基本属性:

        //对象数组:ArrayList的底层数据结构
        private transient Object[] elementData;
        //elementData中已存放的元素的个数,注意:不是elementData的容量
        private int size;

    注意:

    • transient关键字的作用:在采用Java默认的序列化机制的时候,被该关键字修饰的属性不会被序列化。
    • ArrayList类实现了java.io.Serializable接口,即采用了Java默认的序列化机制
    • 上面的elementData属性采用了transient来修饰,表明其不使用Java默认的序列化机制来实例化,但是该属性是ArrayList的底层数据结构,在网络传输中一定需要将其序列化,之后使用的时候还需要反序列化,那不采用Java默认的序列化机制,那采用什么呢?直接翻到源码的最下边有两个方法,发现ArrayList自己实现了序列化和反序列化的方法
      /**
           * Save the state of the <tt>ArrayList</tt> instance to a stream (that is,
           * serialize it).
           * 
           * @serialData The length of the array backing the <tt>ArrayList</tt>
           *             instance is emitted (int), followed by all of its elements
           *             (each an <tt>Object</tt>) in the proper order.
           */
          private void writeObject(java.io.ObjectOutputStream s)
                  throws java.io.IOException {
              // Write out element count, and any hidden stuff
              int expectedModCount = modCount;
              s.defaultWriteObject();
      
              // Write out array length
              s.writeInt(elementData.length);
      
              // Write out all elements in the proper order.
              for (int i = 0; i < size; i++)
                  s.writeObject(elementData[i]);
      
              if (modCount != expectedModCount) {
                  throw new ConcurrentModificationException();
              }
      
          }
      
          /**
           * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
           * deserialize it).
           */
          private void readObject(java.io.ObjectInputStream s)
                  throws java.io.IOException, ClassNotFoundException {
              // Read in size, and any hidden stuff
              s.defaultReadObject();
      
              // Read in array length and allocate array
              int arrayLength = s.readInt();
              Object[] a = elementData = new Object[arrayLength];
      
              // Read in all elements in the proper order.
              for (int i = 0; i < size; i++)
                  a[i] = s.readObject();
          }

    构造器:

        /**
         * 创建一个容量为initialCapacity的空的(size==0)对象数组
         */
        public ArrayList(int initialCapacity) {
            super();//即父类protected AbstractList() {}
            if (initialCapacity < 0)
                throw new IllegalArgumentException("Illegal Capacity:" + initialCapacity);
            this.elementData = new Object[initialCapacity];
        }
    
        /**
         * 默认初始化一个容量为10的对象数组
         */
        public ArrayList() {
            this(10);//即上边的public ArrayList(int initialCapacity){}构造器
        }

    在我们执行new ArrayList<String>()时,会调用上边的无参构造器,创造一个容量为10的对象数组。

    在我们执行new ArrayList<String>(2)时,会调用上边的public ArrayList(int initialCapacity),创造一个容量为2的对象数组。

    注意:

    • 上边有参构造器的super()方法是ArrayList父类AbstractList的构造方法,这个构造方法如下,是一个空构造方法:
          protected AbstractList() {
          }
    • 在实际使用中,如果我们能对所需的ArrayList的大小进行判断,有两个好处:
      • 节省内存空间(eg.我们只需要放置两个元素到数组,new ArrayList<String>(2))
      • 避免数组扩容(下边会讲)引起的效率下降(eg.我们只需要放置大约37个元素到数组,new ArrayList<String>(40))

    2.2、往ArrayList中添加对象(常见的两个方法add(E)和addAll(Collection<? extends E> c))

    2.2.1、add(E)

    strList2.add("hello");

    ArrayList源代码:

        /**
         * 向elementData中添加元素
         */
        public boolean add(E e) {
            ensureCapacity(size + 1);//确保对象数组elementData有足够的容量,可以将新加入的元素e加进去
            elementData[size++] = e;//加入新元素e,size加1
            return true;
        }
        /**
         * 确保数组的容量足够存放新加入的元素,若不够,要扩容
         */
        public void ensureCapacity(int minCapacity) {
            modCount++;
            int oldCapacity = elementData.length;//获取数组大小(即数组的容量)
            //当数组满了,又有新元素加入的时候,执行扩容逻辑
            if (minCapacity > oldCapacity) {
                Object oldData[] = elementData;
                int newCapacity = (oldCapacity * 3) / 2 + 1;//新容量为旧容量的1.5倍+1
                if (newCapacity < minCapacity)//如果扩容后的新容量还是没有传入的所需的最小容量大或等于(主要发生在addAll(Collection<? extends E> c)中)
                    newCapacity = minCapacity;//新容量设为最小容量
                elementData = Arrays.copyOf(elementData, newCapacity);//复制新容量
            }
        }

    在上述代码的扩容结束后,调用了Arrays.copyOf(elementData, newCapacity)方法,这个方法中:对于我们这里而言,先创建了一个新的容量为newCapacity的对象数组,然后使用System.arraycopy()方法将旧的对象数组复制到新的对象数组中去了。

    注意:

    • modCount变量用于在遍历集合(iterator())时,检测是否发生了add、remove操作。

    2.2.2、addAll(Collection<? extends E> c)

    使用方式:

            List<String> strList = new ArrayList<String>();
            strList.add("jigang");
            strList.add("nana");
            strList.add("nana2");
            
            List<String> strList2 = new ArrayList<String>(2);
            strList2.addAll(strList);

    源代码:

        /**
         * 将c全部加入elementData
         */
        public boolean addAll(Collection<? extends E> c) {
            Object[] a = c.toArray();//将c集合转化为对象数组a
            int numNew = a.length;//获取a对象数组的容量
            ensureCapacity(size + numNew);//确保对象数组elementData有足够的容量,可以将新加入的a对象数组加进去
            System.arraycopy(a, 0, elementData, size, numNew);//将对象数组a拷贝到elementData中去
            size += numNew;//重新设置elementData中已加入的元素的个数
            return numNew != 0;//若加入的是空集合则返回false
        }

    注意:

    • 从上述代码可以看出,若加入的c是空集合,则返回false
    • ensureCapacity(size + numNew);这个方法在上边讲
    • System.arraycopy()方法定义如下:
      public static native void arraycopy(Object src,  int  srcPos, Object dest, int destPos,  int length);

      将数组src从下标为srcPos开始拷贝,一直拷贝length个元素到dest数组中,在dest数组中从destPos开始加入先的srcPos数组元素。

    除了以上两种常用的add方法外,还有如下两种:

    2.2.3、add(int index, E element)

        /**
         * 在特定位置(只能是已有元素的数组的特定位置)index插入元素E
         */
        public void add(int index, E element) {
            //检查index是否在已有的数组中
            if (index > size || index < 0)
                throw new IndexOutOfBoundsException("Index:"+index+",Size:"+size);
            ensureCapacity(size + 1);//确保对象数组elementData有足够的容量,可以将新加入的元素e加进去
            System.arraycopy(elementData, index, elementData, index+1, size-index);//将index及其后边的所有的元素整块后移,空出index位置
            elementData[index] = element;//插入元素
            size++;//已有数组元素个数+1
        }

    注意:

    • index<=size才行,并不是index<elementData.length

    2.2.4、set(int index, E element)

        /**
         * 更换特定位置index上的元素为element,返回该位置上的旧值
         */
        public E set(int index, E element) {
            RangeCheck(index);//检查索引范围
            E oldValue = (E) elementData[index];//旧值
            elementData[index] = element;//该位置替换为新值
            return oldValue;//返回旧值
        }

    2.3、获取ArrayList中的单个对象(get(int index))

    实现方式:

            ArrayList<String> strList2 = new ArrayList<String>(2);
            strList2.add("hello");
            strList2.add("nana");
            strList2.add("nana2");
            System.out.println(strList2.get(0));

    源代码:

        /**
         * 按照索引查询对象E
         */
        public E get(int index) {
            RangeCheck(index);//检查索引范围
            return (E) elementData[index];//返回元素,并将Object转型为E
        }
        /**
         * 检查索引index是否超出size-1
         */
        private void RangeCheck(int index) {
            if (index >= size)
                throw new IndexOutOfBoundsException("Index:"+index+",Size:"+size);
        }

    注:这里对index进行了索引检查,是为了将异常内容写的详细一些并且将检查的内容缩小(index<0||index>=size,注意这里的size是已存储元素的个数);

    事实上不检查也可以,因为对于数组而言,如果index不满足要求(index<0||index>=length,注意这里的length是数组的容量),都会直接抛出数组越界异常,而假设数组的length为10,当前的size是2,你去计算array[9],这时候得出是null,这也是上边get为什么减小检查范围的原因。

    2.4、删除ArrayList中的对象

    2.4.1、remove(Object o)

    使用方式:

    strList2.remove("hello");

    源代码:

        /**
         * 从前向后移除第一个出现的元素o
         */
        public boolean remove(Object o) {
            if (o == null) {//移除对象数组elementData中的第一个null
                for (int index = 0; index < size; index++)
                    if (elementData[index] == null) {
                        fastRemove(index);
                        return true;
                    }
            } else {//移除对象数组elementData中的第一个o
                for (int index = 0; index < size; index++)
                    if (o.equals(elementData[index])) {
                        fastRemove(index);
                        return true;
                    }
            }
            return false;
        }
    
        /*
         * 删除单个位置的元素,是ArrayList的私有方法
         */
        private void fastRemove(int index) {
            modCount++;
            int numMoved = size - index - 1;
            if (numMoved > 0)//删除的不是最后一个元素
                System.arraycopy(elementData, index + 1, elementData, index,numMoved);//删除的元素到最后的元素整块前移
            elementData[--size] = null; //将最后一个元素设为null,在下次gc的时候就会回收掉了
        }

     2.4.2、remove(int index)

    使用方式:

    strList2.remove(0);

    源代码:

        /**
         * 删除指定索引index下的元素,返回被删除的元素
         */
        public E remove(int index) {
            RangeCheck(index);//检查索引范围
    
            E oldValue = (E) elementData[index];//被删除的元素
            fastRemove(index);
            return oldValue;
        }

    注意:

    • remove(Object o)需要遍历数组,remove(int index)不需要,只需要判断索引符合范围即可,所以,通常:后者效率更高。

     2.5、判断对象是否存在于ArrayList中(contains(E)

    源代码:

        /**
         * 判断动态数组是否包含元素o
         */
        public boolean contains(Object o) {
            return indexOf(o) >= 0;
        }
    
        /**
         * 返回第一个出现的元素o的索引位置
         */
        public int indexOf(Object o) {
            if (o == null) {//返回第一个null的索引
                for (int i = 0; i < size; i++)
                    if (elementData[i] == null)
                        return i;
            } else {//返回第一个o的索引
                for (int i = 0; i < size; i++)
                    if (o.equals(elementData[i]))
                        return i;
            }
            return -1;//若不包含,返回-1
        }
    
        /**
         * 返回最后一个出现的元素o的索引位置
         */
        public int lastIndexOf(Object o) {
            if (o == null) {
                for (int i = size - 1; i >= 0; i--)
                    if (elementData[i] == null)
                        return i;
            } else {
                for (int i = size - 1; i >= 0; i--)
                    if (o.equals(elementData[i]))
                        return i;
            }
            return -1;
        }

    注意:

    • indexOf(Object o)返回第一个出现的元素o的索引;lastIndexOf(Object o)返回最后一个o的索引

    2.6、遍历ArrayList中的对象(iterator())

    使用方式:

            List<String> strList = new ArrayList<String>();
            strList.add("jigang");
            strList.add("nana");
            strList.add("nana2");
            
            Iterator<String> it = strList.iterator();
            while (it.hasNext()) {
                System.out.println(it.next());
            }

    源代码:iterator()方法是在AbstractList中实现的,该方法返回AbstractList的一个内部类Itr对象

        public Iterator<E> iterator() {
            return new Itr();//返回一个内部类对象
        }

    Itr:

        private class Itr implements Iterator<E> {
            
            int cursor = 0;//标记位:标记遍历到哪一个元素
            int expectedModCount = modCount;//标记位:用于判断是否在遍历的过程中,是否发生了add、remove操作
    
            //检测对象数组是否还有元素
            public boolean hasNext() {
                return cursor != size();//如果cursor==size,说明已经遍历完了,上一次遍历的是最后一个元素
            }
    
            //获取元素
            public E next() {
                checkForComodification();//检测在遍历的过程中,是否发生了add、remove操作
                try {
                    E next = get(cursor++);
                    return next;
                } catch (IndexOutOfBoundsException e) {//捕获get(cursor++)方法的IndexOutOfBoundsException
                    checkForComodification();
                    throw new NoSuchElementException();
                }
            }
    
            //检测在遍历的过程中,是否发生了add、remove等操作
            final void checkForComodification() {
                if (modCount != expectedModCount)//发生了add、remove操作,这个我们可以查看add等的源代码,发现会出现modCount++
                    throw new ConcurrentModificationException();
            }
        }

    遍历的整个流程结合"使用方式"与"Itr的注释"来看。注:上述的Itr我去掉了一个此时用不到的方法和属性。

    三、总结

    • ArrayList基于数组方式实现,无容量的限制(会扩容)
    • 添加元素时可能要扩容(所以最好预判一下),删除元素时不会减少容量(若希望减少容量,trimToSize()),删除元素时,将删除掉的位置元素置为null,下次gc就会回收这些元素所占的内存空间。
    • 线程不安全
    • add(int index, E element):添加元素到数组中指定位置的时候,需要将该位置及其后边所有的元素都整块向后复制一位
    • get(int index):获取指定位置上的元素时,可以通过索引直接获取(O(1))
    • remove(Object o)需要遍历数组
    • remove(int index)不需要遍历数组,只需判断index是否符合条件即可,效率比remove(Object o)高
    • contains(E)需要遍历数组

    做以上总结,主要是为了与后边的LinkedList作比较。

    elementData

    第三章 LinkedList源码解析

    一、对于LinkedList需要掌握的八点内容

    • LinkedList的创建:即构造器
    • 往LinkedList中添加对象:即add(E)方法
    • 获取LinkedList中的单个对象:即get(int index)方法
    • 修改LinkedList中的指定索引的节点的数据set(int index, E element)
    • 删除LinkedList中的对象:即remove(E),remove(int index)方法
    • 遍历LinkedList中的对象:即iterator,在实际中更常用的是增强型的for循环去做遍历
    • 判断对象是否存在于LinkedList中:contain(E)
    • LinkedList中对象的排序:主要取决于所采取的排序算法(以后讲)

    二、源码分析

    2.1、LinkedList的创建

    实现方式:

    List<String> strList0 = new LinkedList<String>();

    源代码:在读源代码之前,首先要知道什么是环形双向链表,参考《算法导论(第二版)》P207

        private transient Entry<E> header = new Entry<E>(null, null, null);//底层是双向链表,这时先初始化一个空的header节点
        private transient int size = 0;//链表中的所存储的元素个数
    
        /**
         * 构造环形双向链表
         */
        public LinkedList() {
            header.next = header.previous = header;//形成环形双向链表
        }

    Entry是LinkedList的一个内部类:

        /**
         * 链表节点
         */
        private static class Entry<E> {
            E element;            //链表节点所存储的数据
            Entry<E> next;        //当前链表节点的下一节点
            Entry<E> previous;    //当前链表节点的前一个节点
    
            Entry(E element, Entry<E> next, Entry<E> previous) {
                this.element = element;
                this.next = next;
                this.previous = previous;
            }
        }

    执行完上述的无参构造器后:形成的空环形双向链表如下:

    其中,左上角为previous,右下角为next

    2.2、往LinkedList中添加对象(add(E e))

    实现方式:

    strList0.add("hello");

    源代码:

        /**
         * 在链表尾部增加新节点,新节点封装的数据为e
         */
        public boolean add(E e) {
            addBefore(e, header);//在链表尾部增加新节点,新节点封装的数据为e
            return true;
        }
        /*
         * 在链表指定节点entry后增加新节点,新节点封装的数据为e
         */
        private Entry<E> addBefore(E e, Entry<E> entry) {
            Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
            newEntry.previous.next = newEntry;//新节点的前一个节点的下一节点为该新节点
            newEntry.next.previous = newEntry;//新节点的下一个节点的前一节点为该新节点
            size++;            //链表中元素个数+1
            modCount++;        //与ArrayList相同,用于在遍历时查看是否发生了add和remove操作
            return newEntry;
        }

    在添加一个元素后的新环形双向链表如下:

    在上述的基础上,再调用一次add(E)后,新的环形双向链表如下:

    这里,结合着代码注释与图片去看add(E)的源代码就好。

    注意:在添加元素方面LinkedList不需要考虑数组扩容和数组复制,只需要新建一个对象,但是需要修改前后两个对象的属性。

    2.3、获取LinkedList中的单个对象(get(int index))

     实现方式:

    strList.get(0);//注意:下标从0开始

    源代码:

        /**
         * 返回索引值为index节点的数据,index从0开始计算
         */
        public E get(int index) {
            return entry(index).element;
        }
        /**
         * 获取指定index索引位置的节点(需要遍历链表)
         */
        private Entry<E> entry(int index) {
            //index:0~size-1
            if (index < 0 || index >= size)
                throw new IndexOutOfBoundsException("Index:"+index+", Size:"+size);
            Entry<E> e = header;//头节点:既作为头节点也作为尾节点
            if (index < (size >> 1)) {//index<size/2,则说明index在前半个链表中,从前往后找
                for (int i = 0; i <= index; i++)
                    e = e.next;
            } else {//index>=size/2,则说明index在后半个链表中,从后往前找
                for (int i = size; i > index; i--)
                    e = e.previous;
            }
            return e;
        }

    注意:

    • 链表节点的按索引查找,需要遍历链表;而数组不需要。
    • header节点既是头节点也是尾节点
    • 双向链表的查找,先去判断索引值index是否小于size/2,若小于,从header节点开始,从前往后找;若大于等于,从header节点开始,从后往前找
    • size>>1,右移一位等于除以2;左移一位等于乘以2

    2.4、修改LinkedList中指定索引的节点的数据:set(int index, E element)

    使用方式:

    strList.set(0, "world");

    源代码:

        /**
         * 修改指定索引位置index上的节点的数据为element
         */
        public E set(int index, E element) {
            Entry<E> e = entry(index);//查找index位置的节点
            E oldVal = e.element;//获取该节点的旧值
            e.element = element;//将新值赋给该节点的element属性
            return oldVal;//返回旧值
        }

    注意:entry(int index)查看上边

    2.5、删除LinkedList中的对象

    2.5.1、remove(Object o)

    使用方式:

    strList.remove("world")

    源代码:

        /**
         * 删除第一个出现的指定元数据为o的节点
         */
        public boolean remove(Object o) {
            if (o == null) {//从前往后删除第一个null
                //遍历链表
                for (Entry<E> e = header.next; e != header; e = e.next) {
                    if (e.element == null) {
                        remove(e);
                        return true;
                    }
                }
            } else {
                for (Entry<E> e = header.next; e != header; e = e.next) {
                    if (o.equals(e.element)) {
                        remove(e);
                        return true;
                    }
                }
            }
            return false;
        }
        /*
         * 删除节点e
         */
        private E remove(Entry<E> e) {
            //header节点不可删除
            if (e == header)
                throw new NoSuchElementException();
    
            E result = e.element;
            //调整要删除节点的前后节点的指针指向
            e.previous.next = e.next;
            e.next.previous = e.previous;
            //将要删除元素的三个属性置空
            e.next = e.previous = null;
            e.element = null;
            
            size--;//size-1
            modCount++;
            return result;
        }

    注意:

    • header节点不可删除

     2.5.2、remove(int index)

    使用方式:

    strList.remove(0);

    源代码:

        /**
         * 删除指定索引的节点
         */
        public E remove(int index) {
            return remove(entry(index));
        }

    注意:

    • remove(entry(index))见上边
    • remove(Object o)需要遍历链表,remove(int index)也需要

     2.6、判断对象是否存在于LinkedList中(contains(E)

    源代码:

        /**
         * 链表中是否包含指定数据o的节点
         */
        public boolean contains(Object o) {
            return indexOf(o) != -1;
        }
        /**
         * 从header开始,查找第一个出现o的索引
         */
        public int indexOf(Object o) {
            int index = 0;
            if (o == null) {//从header开始,查找第一个出现null的索引
                for (Entry e = header.next; e != header; e = e.next) {
                    if (e.element == null)
                        return index;
                    index++;
                }
            } else {
                for (Entry e = header.next; e != header; e = e.next) {
                    if (o.equals(e.element))
                        return index;
                    index++;
                }
            }
            return -1;
        }

    注意:

    • indexOf(Object o)返回第一个出现的元素o的索引

    2.7、遍历LinkedList中的对象(iterator())

    使用方式:

            List<String> strList = new LinkedList<String>();
            strList.add("jigang");
            strList.add("nana");
            strList.add("nana2");
            
            Iterator<String> it = strList.iterator();
            while (it.hasNext()) {
                System.out.println(it.next());
            }

    源代码:iterator()方法是在父类AbstractSequentialList中实现的,

        public Iterator<E> iterator() {
            return listIterator();
        }

    listIterator()方法是在父类AbstractList中实现的,

        public ListIterator<E> listIterator() {
            return listIterator(0);
        }

    listIterator(int index)方法是在父类AbstractList中实现的,

        public ListIterator<E> listIterator(final int index) {
            if (index < 0 || index > size())
                throw new IndexOutOfBoundsException("Index: " + index);
    
            return new ListItr(index);
        }

    该方法返回AbstractList的一个内部类ListItr对象

    ListItr:

        private class ListItr extends Itr implements ListIterator<E> {
            ListItr(int index) {
                cursor = index;
            }

    上边这个类并不完整,它继承了内部类Itr,还扩展了一些其他方法(eg.向前查找方法hasPrevious()等),至于hasNext()/next()等方法还是来自于Itr的。

    Itr:

            
            int cursor = 0;//标记位:标记遍历到哪一个元素
            int expectedModCount = modCount;//标记位:用于判断是否在遍历的过程中,是否发生了add、remove操作
    
            //检测对象数组是否还有元素
            public boolean hasNext() {
                return cursor != size();//如果cursor==size,说明已经遍历完了,上一次遍历的是最后一个元素
            }
    
            //获取元素
            public E next() {
                checkForComodification();//检测在遍历的过程中,是否发生了add、remove操作
                try {
                    E next = get(cursor++);
                    return next;
                } catch (IndexOutOfBoundsException e) {//捕获get(cursor++)方法的IndexOutOfBoundsException
                    checkForComodification();
                    throw new NoSuchElementException();
                }
            }
    
            //检测在遍历的过程中,是否发生了add、remove等操作
            final void checkForComodification() {
                if (modCount != expectedModCount)//发生了add、remove操作,这个我们可以查看add等的源代码,发现会出现modCount++
                    throw new ConcurrentModificationException();
            }
        }

    注:

    • 上述的Itr我去掉了一个此时用不到的方法和属性。
    • 这里的get(int index)方法参照2.3所示。

    三、总结

    • LinkedList基于环形双向链表方式实现,无容量的限制
    • 添加元素时不用扩容(直接创建新节点,调整插入节点的前后节点的指针属性的指向即可)
    • 线程不安全
    • get(int index):需要遍历链表
    • remove(Object o)需要遍历链表
    • remove(int index)需要遍历链表
    • contains(E)需要遍历链表

    四种List实现类的对比总结

    1、ArrayList

    • 非线程安全
    • 基于对象数组
    • get(int index)不需要遍历数组,速度快;
    • iterator()方法中调用了get(int index),所以速度也快
    • set(int index, E e)不需要遍历数组,速度快
    • add方法需要考虑扩容与数组复制问题,速度慢
    • remove(Object o)需要遍历数组,并复制数组元素,速度慢
    • remove(int index)不需要遍历数组,需要复制数组元素,但不常用
    • contain(E)需要遍历数组

    2、LinkedList

    • 非线程安全
    • 基于环形双向链表
    • get(int index)需要遍历链表,速度慢;
    • iterator()方法中调用了get(int index),所以速度也慢
    • set(int index, E e)方法中调用了get(int index),所以速度也慢
    • add方法不需要考虑扩容与数组复制问题,只需创建新对象,再将新对象的前后节点的指针指向重新分配一下就好,速度快
    • remove(Object o)需要遍历链表,但不需要复制元素,只需将所要删除的对象的前后节点的指针指向重新分配一下以及将所要删除的对象的三个属性置空即可,速度快
    • remove(int index)需要遍历链表,但不需要复制元素,只需将所要删除的对象的前后节点的指针指向重新分配一下以及将所要删除的对象的三个属性置空即可,但不常用
    • contain(E)需要遍历链表

    3、Vector(线程安全的ArrayList)

    • 线程安全
    • 扩容机制与ArrayList不同

    4、Stack(继承于Vector)

    • 线程安全
    • 效率低下,可采用双端队列Deque或LinkedList来实现,Deque用的较多

    总结:

    • 在查询(get)、遍历(iterator)、修改(set)使用的比较多的情况下,用ArrayList
    • 在增加(add)、删除(remove)使用比较多的情况下,用LinkedList
    • 在需要线程安全而且对效率要求比较低的情况下,使用Vector,当然,实现ArrayList线程安全的方法也有很多,以后再说
    • 在需要使用栈结构的情况下,使用Deque,Stack废弃就行了
    1.扩容机制

      1.扩容是懒惰式的,即没有添加元素前,即时指定了容量,也不会真正的创建数组

      2. add(Object o) 方法首次扩容为10,再次扩容为上次的1.5倍

      3. addAll(Collection c) 方法首次扩容(没有元素)为10,或者添加的元素实际个数,取两者间的最大值

      4. addAll(Collection c) 方法再次扩容(有元素时)取原容量1.5倍或者实际元素个数,取两者间最大值.

    2. fail-fast 与 fail-safe 机制

      1. fail-fast : 一旦发现遍历集合的同时,其他人来修改则立即抛出异常

      2. fail-safe : 发现遍历集合的同时其他人来修改,应当能有应对策略,例如牺牲一部分一致性,来让整个遍历运行完成

      3. ArrayList 是fail-fast的典型代表,遍历同时不能修改,底层实现是在遍历前记录了集合的修改次数,在循环过程中如果发现集合的修改次数与遍历前记录的不一致,直接抛出并发修改异常

      4. CopyOnWriteArrayList 是 fail-safe的典型代表,遍历的同时可以修改,原理是读写分离,就是在修改集合的时候,底层会创建一个新的数组,复制出之前的数据并添加修改后的数据,但是遍历时使用的还是旧的数组,所以不会报错,但是遍历时也不会读取到新添加的数据.

    3. ArrayList 与 LinkedList 的比较

      1. ArrayList

        1. 基于数组,需要连续内存

        2. 随机访问快(指根据下标访问)

        3. 尾部插入,删除性能可以,其他部分插入,删除都会移动数据,因此性能低

        4. 可以利用 cpu 的缓存,通过局部性原理

      2. LinkedList

        1. 基于双向链表,无需连续内存

        2. 随机访问慢 (要沿着链表遍历)

        3. 头尾插入,删除性能高,但是中间插入查找位置效率慢,所以性能低

        4. 占用内存多

  • 相关阅读:
    Linux下tomcat中多项目配置druid报错的问题
    chrome实用快捷键速记
    count 与 group by
    H5相机上传图片压缩
    图片通过转base64上传
    内网之间访问
    composer 加载第三方类库
    访问一个项目生成两个session文件原因
    arttemplate.js 如何不直接输出html代码
    Tomcat 支持多少并发量
  • 原文地址:https://www.cnblogs.com/hanease/p/16295774.html
Copyright © 2020-2023  润新知