arrayList源代码

好久不写博客啦 最近一直忙着面试,昨天面试官问我读没读过arraylist的源代码 瞬间蒙蔽,今天总结一下,以前感觉源代码都是好高大上的东西,今天自己结合百度读啦一下,发现源代码也并不难,最近会吧jdk中的源代码自己总结一下。

我用的是jdk1.7

这篇博客只总结主要的 构造器 add get set等方法 remove   iterator contains 其余的不去总结。有兴趣可以自己去读一下 其实很简单的 我以前就是以为难从来没读过(逃。。)。

 private static final long serialVersionUID = 8683452581122892189L;//和序列化有关 

    /**
     * Default initial capacity. 默认初始容量 并不是和hashmap的18
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.底层就是一个Object的数组 就是这么简单 后面会看到对它的一些基本操作
     */
    private static final Object[] 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 == EMPTY_ELEMENTDATA will be expanded to
     * DEFAULT_CAPACITY when the first element is added.
     */
    private transient Object[] elementData;

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

接下来我们看一下构造器

public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }
public ArrayList() {
        super();
        this.elementData = EMPTY_ELEMENTDATA;
    }
 public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }

过程也很简单 如果是空就直接将EMPTY_ELEMENTDATA赋值给elementData 如果不是空 就直接给与一个new Object(),当然先要判读传入的参数是不是大于0;如果传入的是一个Collection就就调用toArray()。 

public boolean isEmpty() {
        return size == 0;
    }
public int size() {
        return size;
    }
public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

这三个方法不用解释啦。

public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
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;
    }

注意这里和我们平时的认知不太一样(最起码和我的不一样) contains 并不是在自己里面遍历查找 返回ture和false 而是调用

indexof 返回的是一个数字 根据这个数字是否大于0进行判断。

   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);
        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进行保对象数组elementData有足够的容量,可以将新加入的元素e加进去  注意 int newCapacity = oldCapacity + (oldCapacity >> 1); 这里是扩展1.5倍的意思。因为array大小是固定的 所以在grow最后调用的是一个Array.copyOf(); 之后就是讲添加的元素 elementData[size++] = e; 返回true。
 

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

        return elementData(index);
    }
 public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

get和set都要通过rangeCheck先检查越不越界 之后进行调用。

 public Iterator<E> iterator() {
        return new Itr();
    }
private class Itr implements Iterator<E> {
        
        int cursor = 0;//标记位:标记遍历到哪一个元素
        int expectedModCount = modCount;//标记位:用于判断是否在遍历的过程中,是否发生了add、remove操作

        //检测对象数组是否还有元素
        public boolean hasNext() {
            return cursor != size();//如果cursor==size,说明已经遍历完了,上一次遍历的是最后一个元素
        }

        //获取元素
        public E next() {
            checkForComodification();//检测在遍历的过程中,是否发生了add、remove操作
            try {
                E next = get(cursor++);
                return next;
            } catch (IndexOutOfBoundsException e) {//捕获get(cursor++)方法的IndexOutOfBoundsException
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        //检测在遍历的过程中,是否发生了add、remove等操作
        final void checkForComodification() {
            if (modCount != expectedModCount)//发生了add、remove操作,这个我们可以查看add等的源代码,发现会出现modCount++
                throw new ConcurrentModificationException();
        }
    }


 

猜你喜欢

转载自blog.csdn.net/qq_40182703/article/details/82686173