【Java基础】ArrayList

一、知识点概要

    1. ArrayList是一个泛型容器,默认的容量大小为10, 每次扩容大小为当前容量大小的一半

    2. ArrayList的实现基于数组,内部使用Object[]对象数组存储元素,所以能快速的随机访问数组元素

    3. ArrayList是非线程安全的,内部没有同步机制

    4. ArrayList内部定义了两个迭代器类Itr和ListItr,支持通过迭代器进行遍历,其中Itr继承自Iterator, ListItr继承自Itr。通过使用Itr可以实现遍历过程中删除元素,而通过ListItr既可以实现遍历过程删除元素,也可以实现遍历过程增加(add)和修改(set)元素。foreach对ArrayList的遍历实现就是通过Itr实现的。

	List<String> arrayList = new ArrayList<>();
	arrayList.add("A");
	arrayList.add("B");
	arrayList.add("C");
	arrayList.add("B");
	ListIterator<String> listIterator = arrayList.listIterator();
	while (listIterator.hasNext()) {
		String string = listIterator.next();
		if ("B".equals(string)) {
			listIterator.add("Z");
		} else if ("C".equals(string)) {
			listIterator.remove();
		}
	}
	System.out.println(arrayList);

上诉代码输出结果为:[A, B, Z, B, Z]

二、源码分析

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * 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
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    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);
        }
    }

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

    /**
     * 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();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

从上述源码部分可以看到,ArrayList是一个泛型定义,这保证了ArrayList可作为各种对象的容器。同时定义了三个构造方法:

1. 默认构造方法。默认构造方法构建的ArrayList只赋值了一个空的数组,并没有分配存储空间。从后续代码可以看到默认构造方法构建的ArrayList,其空间分配是在首次添加元素时,进行分配的,首次分配大小为10。

2. 整型参构造方法。此构造方法带了一个容量大小的参数,如果参数小于0,直接抛异常。如果参数大于0,则分配参数大小的空间。如果参数为0,则赋值了一个空的数组对象,此处需要注意与默认构造方法赋予的空的数组对象不是同一个,这里产生的一个差异就是在扩容时的差异。默认构造方法首次扩容,直接扩充到10,后续每次扩充当前容量的一半; 而如果使用大小为0的构造方法,首次扩充为1, 再扩充为2,后续则每次扩充当前容量的一半。(此处差异要参考源码中的扩容方法来分析)

3. Collection对象的构造方法。此构造方法直接传入了一个元素集合作为参数,此时如果元素集合不为空,则会直接分配集合元素大小的数组来存储集合元素。如果元素集合为空,则与传参数0的构造方法等效。

    /**
     * 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);
        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);
    }

上述代码,则为ArrayList扩容的部分关键逻辑代码,从上述代码可以看出每次扩容大小为当前容量的一半。如果扩容后的大小比最小容量要求小,则会直接扩容到最小容量要求。同时,如果扩容后的空间超过阈值,则会取一个最大值。最后,在扩容完成后,会将当前数组的内容,拷贝到新分配的空间中去。

从此部分代码就可以理解,如果我们能预知ArrayList的大小,则可以直接通过带容量大小参数的构造函数来构建ArrayList对象。这样可以减少后续的扩容动作,进而避免扩容所带来的的内存重新分配消耗和数据拷贝的消耗。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值