Java ArrayList 构造函数源码分析

ArrayList内部实现详解:容量、size与构造方法
本文深入解析ArrayList的内部实现机制,包括其底层维护的Object数组、容量与size属性,以及不同构造方法的使用场景。了解如何通过指定初始容量创建ArrayList实例,以及如何自动维护数组长度与size值。

1.  ArrayList 在底层维护一个 Object[] ,如果你使用了泛型,其实是维护一个泛型指定类型的数组对象

    /**
     * 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 E[] elementData;

    ArrayList维护的数组的长度表示一个“容量”,用户一般不主动维护“容量”这个值,我们通常要使用的是数组的长度,也就是你add了多少个对象。

2.  用户通过ArrayList对象的size()方法得到ArrayList实例中对象的数目

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

 

/**
     * Returns the number of elements in this list.
     *
     * @return  the number of elements in this list.
     */
    public int size() {
	return size;
    }

    当我们进行add remove等操作的时候,ArrayList对象会自动维护size值

3. ArrayList 的构造方法

    (1)指定“容量”的构造方法

/**
     * 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 = (E[])new Object[initialCapacity];
    }

    如果在实例化ArrayList类的时候,指定了“容量”,那么ArrayList会生成一个指定容量大小的数组

    (2)默认构造方法

    

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

    (3) 构造一个与指定集合内容相同的ArrayList

    

/**
     * @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) {
        size = c.size();
        // Allow 10% room for growth
        int capacity = (int) Math.min((size*110L)/100, Integer.MAX_VALUE);
        elementData = (E[]) c.toArray(new Object[capacity]);
    }

    使用这个构造方法生成的对象与参数Collection<? extends E> c 的hashCode值是相同的,但是二者互不影响。

    此时,ArrayList实例的“容量”是参数Collection<? extends E> c 的size(一定要注意是size,不是c的“容量”)的110%+1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值