jdk6标准类库源码解读 之 数据结构 (一) ArrayList<E>

最近受到一次面试的启发,开始看jdk6的标准源码,在这里记录下自己看的过程中的体会,和大家分享。

从最常用的数据结构开始 

     ArrayList<E>

  • 此对象的存储采用的是标准的Object数组(elementData)进行存储,同时使用一个整形记录数组(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.
     */
    private transient Object[] elementData;

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;
  • 对象默认初始化存储容量为10
    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
	this(10);
    }
  •  对象中的存储数组elementData会随着需要存储数据的增加而扩大。在调用对象的add方法时,arraylist会首先判断容量是否足够,不够时,采用newCapacity = (oldCapacity * 3)/2 + 1的策略,进行扩充。此策略只计算一次,如果扔不足够,则直接按照新的容量进行扩展。
    public boolean add(E e) {
        ensureCapacity(size + 1); // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    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);
        }
    }
  • 对象中的存储数组elementData不会随着需要存储数据的减少而缩小。对象只会改变elementData中的数据存储位置,进行迁移,并依赖gc判断移除对象的回收。
    public E remove(int index) {
        RangeCheck(index);

        modCount++;
        E oldValue = (E) elementData[index];

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index + 1, elementData, index, numMoved);
        elementData[--size] = null; // Let gc do its work

        return oldValue;
    }

 

  • indexof采用的是标准的遍历算法,时间复杂度很高,效率很低。并且都是从前开始匹配。contains方法同理。
    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i] == null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

 

上面可以通过源码,更准确的看到标准类库中对象的特点,后面会继续加入其他的数据类型、和标准类库中的其他类。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值