java集合之ArrayList详解

虽说做java开发有一两年了,但是对集合(collection)真的了解吗?老话说的好:温故而知新。今天又来看看java这些集合归纳一下。

我们都知道java存储集合的方式有很多,数组、ArrayList、LinkedList、HashSet、HashMap、HashTable等等,我们今天先来了解下List--ArrayList。

介绍List之前,我们先来说说数组,比如:String[] arrayString = new String[10];我们声明一个存放String类型的数组,长度为10(固定长度,如果没有占满我们的内存还是10个长度的(浪费空间),如果超出会报错的因为长度是固定的哦),我们的数组缺点就是固定长度,但是优点也是很明显的,想要获取指定位置的内容时直接通过下标就能快速获取到数据。那么我们声明变量时也不知道这个变量的长度时怎么办?就要靠我们的ArrayList了。

我们先来看下ArrayList继承关系(我用的jdk1.8):

 我们可以看到ArrayList间接的实现了List接口,直接实现了Cloneable、Serializable等接口和继承了某些类,这样我们就能大概了解了ArrayList有那些功能了,通过实现Cloneable接口,我们猜想应该是可以进行clone的,实现Serializable猜想是进行了序列化的,实现List接口说明是可以进行增删对象的。这是你对一个类的大概理解,接下来我们重点去看下java是怎么实现List接口中对对象的操作的。

    /**
     * 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.
     */
    //这个是ArrayList维护的数据,其实都是放到这里面的,也就是说ArrayList本质是Object[]
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    //这个是这个list的size,也就是Object[]存放数据的长度
    private int size;

我们可以看到ArrayList其实维护的是一个Object[] elementData来存储数据的,有人肯定会想数组不是固定长度的吗?我们待着这个问题来看下源码是如何实现这个的。

    public static void main(String[] args){
        //声明一个可变的list
        List<String> arrayList = new ArrayList<>();
        String abc = new String("abc");
        String bcd = new String("bcd");
        //add一个对象到list中
        arrayList.add(abc);
        arrayList.add(bcd);
        //在指定位置插入对象
        arrayList.add(0,"abcd");
        return;
    }

这是我们平常使用List的步骤,我们一步一步来看。

一:首先是初始化我们的ArrayList对象

List<String> arrayList = new ArrayList<>();//这一步jdk帮我们做了什么?

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

初始化时,jdk只是把一个空数组赋给了elementData,但是ArrayList中不止这一个构造方法,我们一起来看一下其他的。

    /**
     * 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
     */
    //这个构造方法,指定了一个初始化容量,就是elementData的长度
    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 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
     */
    //这个是将其他的collection放到了这个list中
    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;
        }
    }

一个是指定了一个初始化容量也就是elementData的长度,另一个构造方法是将一个collection拼接到了list中。

二:arrayList.add(new String("abc"));是如何动态添加对象的?我们默认我们没有初始化容量,也就是elementData = {}空数组

    /**
     * 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!!
        elementData[size++] = e;
        return true;
    }

    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }

    private void ensureExplicitCapacity(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);//我们可以看到newCapacity这个是新容量,增长的长度是size >> 1(也就是size/2的增长)
        //如果我们之前的长度是初始化的长度10,那么我们增长为10 + (10 >> 1)也就是15
        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);
    }

我们把所有用到的方法都贴了出来,我们一个一个看,首先是add方法:

我们会发现上来先调用了一个ensureCapacityInternal(int minCapacity)方法,先不管,然后就是elementData[size++] = e,我们的对象被放到elementData数组中了,但是我们初始化是elementData明明是个{}(空数组)啊,这时候我们去看下上面的方法具体执行了什么操作才使elementData真正的初始化为了new Object[int]的。最后我们会看到grow()方法中的最后一行elementData进行了赋值操作,接着看我们的Arrays.copyof,然而我们的copy到新数组的长度是多少?(也就是我们list增长容量是多少?),我们主要看我们的grow方法中的newCapacity变量(新数据容量)最后是多少?int newCapacity = oldCapacity + (oldCapacity >> 1);//我们可以看到newCapacity这个是新容量,增长的长度是size >> 1(也就是size/2的增长),比如:如果我们之前的长度是初始化的长度10,那么我们增长为10 + (10 >> 1)也就是15

    /**
     * Copies the specified array, truncating or padding with nulls (if necessary)
     * so the copy has the specified length.  For all indices that are
     * valid in both the original array and the copy, the two arrays will
     * contain identical values.  For any indices that are valid in the
     * copy but not the original, the copy will contain <tt>null</tt>.
     * Such indices will exist if and only if the specified length
     * is greater than that of the original array.
     * The resulting array is of the class <tt>newType</tt>.
     *
     * @param <U> the class of the objects in the original array
     * @param <T> the class of the objects in the returned array
     * @param original the array to be copied
     * @param newLength the length of the copy to be returned
     * @param newType the class of the copy to be returned
     * @return a copy of the original array, truncated or padded with nulls
     *     to obtain the specified length
     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
     * @throws NullPointerException if <tt>original</tt> is null
     * @throws ArrayStoreException if an element copied from
     *     <tt>original</tt> is not of a runtime type that can be stored in
     *     an array of class <tt>newType</tt>
     * @since 1.6
     */
    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

 这个方法是copy数组的实现,所以我们每次add其实就是将原来的数组copy到一个新数组中的。

总结一下:我们的动态数组,每次add的时候都将旧数组中的值copy到一个新数组中,然而我们的新数组的长度是怎样变化的呢?第一次我们进行初始化数组操作,长度为10,随后再次add时,我们按照 size + (size >> 1)增长

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值