`
zero_lx
  • 浏览: 17264 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

深入剖析ArrayList源代码

 
阅读更多

ArrayList这个容器实质上就是个会自动增长的数组,默认初始容量是10,按原容器的1.5倍扩容。在ArrayList里面定义了一个私有的数组。

/**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer.
     */
    private transient Object[] elementData;

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param   initialCapacity   the initial capacity of the list
     * @exception IllegalArgumentException if the specified initial capacity
     *            is negative
     */
    public ArrayList(int initialCapacity) {
	super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
	this.elementData = new Object[initialCapacity];
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
	this(10);
    }

 可以看到无参的构造方法默认调用的是有容量的构造方法,并且初始化给了10。也就是一个数组长度为10的Object类型的数组,从这里也可以看出ArrayList只能存放对象而不能存放原生数据。接下来是最重要的往容器添加数据的方法。

/**
     * 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) {
	ensureCapacity(size + 1);  // Increments modCount!!
	elementData[size++] = e;
	return true;
    }

/**
     * 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) {
	modCount++;
	int oldCapacity = elementData.length;
	if (minCapacity > oldCapacity) {
	    Object oldData[] = elementData;
	    int newCapacity = (oldCapacity * 3)/2 + 1;
    	    if (newCapacity < minCapacity)
		newCapacity = minCapacity;
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
	}
    }
 在往容器添加数据的方法中可以看到每添加一个元素都会调用一次ensureCapacity()方法,也就是添加容器长度的方法。但是传的参数是size+1,而size是容器包含的元素个数。所以每次添加的是包含元素个数+1的值。当然这里会有个判断,但元素个数+1超过原有数组长度的时候,就会执行扩容的动作。新数组的容量会是原数组的1.5倍。int newCapacity = (oldCapacity * 3)/2 + 1,接着会执行一个数组复制的动作。所以说到底ArrayList就是一个会自动增长长度的数组。从add()方法中也可以看出在ArrayList中可以增加重复的元素,并不会判断元素是否相等。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics