jdk源码阅读之ArrayList

ArrayList是一种集合,对于集合的操作不外乎增删查改这么几种,下面就从这几个方面来剖析ArrayList的源代码。
首先看一下ArrayList的声明:

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

从上面的继承关系可以看出ArrayList的父类是AbstractList,实现了List接口,可以随机访问,这也说明内部的存储是使用数组,可以克隆和串行化.

1. 增

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
private void ensureCapacityInternal(int minCapacity) {
        if (elementData == EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);//扩容1.5倍
        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);
    }
public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

add方法首先要保证容量的大小必须大于ArrayList的size大小,保证的原则是如果容量需要扩容,则在grow方法里面扩容1.5倍,然后将旧数组拷贝至新数组。对于插入元素到数组的中间而不是末尾,那么每一次插入都会进行一次拷贝,这样会消耗大量的时间,因此ArrayList这种容器不适合于插入操作。

2. 删

public E remove(int index) {
        rangeCheck(index);

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

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

        return oldValue;
    }
public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

remove的方式有两种,一种是删除指定下表的元素,另一种是根据传入的对象a,若满足a.equals(b),则删除所有满足条件的b对象。
clear方法将所有元素都删除,其实就是将所有的引用都赋值为null,让垃圾回收器去删除堆上真正的对象。

3. 查

public E get(int index) {
        rangeCheck(index);
        return elementData(index);
    }
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;
    }

get方法直接返回对应下标的元素,indexOf方法返回第一个满足equals方法的对象下表,如果没有满足的对象,则返回-1.

4. 改

public E set(int index, E element) {
        rangeCheck(index);
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

set方法将特定位置的元素改为element.

5. 遍历

既然是容器那么就要遍历,当然可以使用for循环,搭配get方法是可以完成遍历的,但是一般来说,对于容器最好的遍历方式是使用迭代器。

public Iterator<E> iterator() {
        return new Itr();
    }
private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size;
        }
		@SuppressWarnings("unchecked")
		public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

iterator()方法返回ArrayList的顺序访问迭代器,这个迭代器是Itr 类的对象,在迭代器有hasNext和next方法,分别用来判断是否有下一个元素和返回下一个元素。使用迭代器一般的方法是:

ArrayList<A> a = new ArrayList<>();
Iterator<A> it = a.iterator();
		while (it.hasNext()) {
			A next = it.next();
			// System.out.print(next.getI());
		}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值