zoukankan      html  css  js  c++  java
  • <原创> JAVA ArrayList源码分析(基于JDK7)

    ArrayList:动态数组。提供了数组的一系类操作,包括增删取存等。下面将对ArrayList的实现源码进行分析。

    ArrayList类中的成员变量:

       
      //这个类实现序列化的接口,也就是类的对象是可序列化的
    //序列化的作用:简单说就是为了保存在内存中的各种对象的状态,并且可以把保存的对象状态再读出来。
      //虽然你可以用你自己的各种各样的方法来保存Object States,
      //但是Java给你提供一种应该比你自己好的保存对象状态的机制,那就是序列化。
      //
      private static final long serialVersionUID = 8683452581122892189L; /** * The array buffer into which the elements of the ArrayList are stored. --存储ArrayList的元素的一个缓冲区。 * The capacity of the ArrayList is the length of this array buffer. -- ArrayList的容量就是这个缓冲区的长度。
    * transient关键字:Java的serialization提供了一种持久化对象实例的机制。当持久化对象时,可能有一个特殊的对象数据成员,我们不想用 serialization机制来保存它。
    * 为了在一个特定对象的一个域上关闭serialization,可以在这个域前加上关键字transient。 当一个对象被序列化的时候,transient型变量的值不包括在序列化的表示中,
    * 然而非transient型的变量是被包括进去的。也就是当ArrayList对象被序列化存储时,这个属性被没有被包含进去。
    */ private transient Object[] elementData; /** * The size of the ArrayList (the number of elements it contains). -- ArrayList的长度。 */ private int size;

    ArrayList的方法介绍:

    1、构造方法:根据参数不同,ArrayList提供了三种不同的构造方法,一种参数为空,一种参数是list的长度,一种是出入另一个collection对象。

    /**
         * Constructs an empty list with the specified initial capacity. --构建特定长度的空的list。
         *
         * @param  initialCapacity  the initial capacity of the list
         * @throws IllegalArgumentException if the specified initial capacity
         *         is negative
         */
        public ArrayList(int initialCapacity) {
            super();
            if (initialCapacity < 0)              //如果传入的参数小于0,那么抛出异常。
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
            this.elementData = new Object[initialCapacity];   //否则根据传入的参数创建一个特定长度的ArrayList缓冲区域。
        }
    
        /**
         * Constructs an empty list with an initial capacity of ten. --默认的长度为10.
         */
        public ArrayList() {
            this(10);
        }
    
        /**
         * Constructs a list containing the elements of the specified
         * collection, in the order they are returned by the collection's
         * iterator.
         *
         * @param c the collection whose elements are to be placed into this list
         * @throws NullPointerException if the specified collection is null
         */
        public ArrayList(Collection<? extends E> c) {
            elementData = c.toArray();
            size = elementData.length;
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        }

    2、添加元素的方法:提供了两种方法,一种在末尾添加,另一种指定特殊位置添加。

    /**
         * Appends the specified element to the end of this list.
         *
         * @param e element to be appended to this list
         * @return <tt>true</tt> (as specified by {@link Collection#add})
         */
        public boolean add(E e) {
            ensureCapacityInternal(size + 1);  // Increments modCount!!//保证ArrayList不会出现数组越界,如果size+1越界,那么扩容1.5倍,具体代码后面展示。
    elementData[size++] = e; //在Array缓冲区末尾加上要添加的元素。 return true; } /** * Inserts the specified element at the specified position in this --在ArrayList中特定的位置插入特定的元素 * list. Shifts the element currently at that position (if any) and --将当前位置的元素(如果有的话)和他之后的元素向右移。 * any subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { rangeCheckForAdd(index); //判断插入的位置是否在0 - size之间,否则抛出IndexOutOfBoundsException 异常。具体算法后面展示 ensureCapacityInternal(size + 1); // Increments modCount!! //保证ArrayList不会出现数组越界,如果size+1越界,那么扩容1.5倍,具体代码后面展示。 System.arraycopy(elementData, index, elementData, index + 1, // Array 复制方法,实现把插入位置之后元素向右移一位的的目的。 size - index); elementData[index] = element; //在目标位置插入元素。 size++; }

    下面介绍 ensureCapacityInternal(size + 1)和 rangeCheckForAdd(index)方法:

      /**
         * Increases the capacity of this <tt>ArrayList</tt> instance, if
         * necessary, to ensure that it can hold at least the number of elements
         * specified by the minimum capacity argument.
         *
         * @param   minCapacity   the desired minimum capacity
         */
        public void ensureCapacity(int minCapacity) {
            if (minCapacity > 0)
                ensureCapacityInternal(minCapacity);
        }
    
        private void ensureCapacityInternal(int minCapacity) {
            modCount++;
            // overflow-conscious code
            if (minCapacity - elementData.length > 0)
                grow(minCapacity);
        }

      /**
         * Increases the capacity to ensure that it can hold at least the
         * number of elements specified by the minimum capacity argument.
         *
         * @param minCapacity the desired minimum capacity
         */
        private void grow(int minCapacity) {
            // overflow-conscious code
            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + (oldCapacity >> 1); 右移一位正好相当于处于2,然后加上原来的就是增加1.5倍。
            if (newCapacity - minCapacity < 0)
                newCapacity = minCapacity;
            if (newCapacity - MAX_ARRAY_SIZE > 0)
                newCapacity = hugeCapacity(minCapacity);
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
        }

        private static int hugeCapacity(int minCapacity) {
            if (minCapacity < 0) // overflow
                throw new OutOfMemoryError();
            return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;
        }
    /** * A version of rangeCheck used by add and addAll. */ private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }

    3、添加一个collection到ArrayList:同样提供两种方法,一种添加在末尾,和add相似,不在赘述。

    4、remove和add正好是一个你想的过程,不在赘述。

    其他的一些方法还有很多,但是常用的就是上边的一些,其余的再次不在多说,感兴趣的可以去查看源码。

    余下问题:

        1、size的修改,跟踪失败了,按理说,每次修改完list之后都要修改size,或者是每次使用size都重新计算,但是这两个都没有发现。

        2、数据全在一个ArrayBuffer中放着的,而这个Buffer是怎么和ArrayList关联的?

      

  • 相关阅读:
    codeforces 1257 E、F
    hdu5954
    Codeforces Round #597 (Div. 2)
    最长公共子序列
    Codeforces Problem
    Vim 编译运行gcc、g++
    【Codeforces Round #107 (Div. 2)】Win or Freeze
    【Codeforces Round #107 (Div. 2)】Quantity of Strings
    【CoreForces Round #104D】Lucky Number 2
    【CoreForces Round #104C】Lucky Conversion
  • 原文地址:https://www.cnblogs.com/yanhuofenhuang/p/3727870.html
Copyright © 2011-2022 走看看