ArrayList 源码分析

2 篇文章 0 订阅
1 篇文章 0 订阅

首先看下ArrayList的关系图

ArrayList 继承自AbstractList,实现了List 、RandomAccess、Cloneable、Serializable接口
点开List接口,你会发现我们常用的方法基本上都在这里,当然,实现都是在ArrayList当中。

再回到ArrayList的源码,我们会发现ArrayList的几大特点:

  • ArrayList维护了一个动态的数组,可以增加或缩减其长度。
  • ArrayList 是线性不安全的,在多线程中操作一个ArrayList需要手动保证数据的同步。
  • 每个ArrayList实例维护了一个capacity的属性,顾名思义,就是集合的容量,且其值会随着数据的变化增长或者衰减。

ArrayList的两大精华

  • 扩容
  • Iterator

首先看下这几个属性

/**
 * 默认的容器大小
 */
private static final int DEFAULT_CAPACITY = 10;

/**
 *一个空的数组
 */
private static final Object[] EMPTY_ELEMENTDATA = {};

/**
 在这里要清楚transient 的含义,被该属性修饰的变量不会被序列化
 */
transient Object[] elementData;

/**
 * 元素长度
 *
 */
private int size;

//这个属性来自AbstrctList  代表的含义是每当ArrayList的结构发生变化的时候 该变量+1;该属性同样使用了transient 修饰,因为没必要持久化。
protected transient int modCount = 0;

大精华之一:扩容:

最常见的add()方法

/**
 * 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;
}

/**
 * Increases the capacity of this <tt>ArrayList</tt> instance, if
 * necessary, to ensure that it can hold at least the number of elements
 * specified by the minimum capacity argument.
 *
 * @param   minCapacity   the desired minimum capacity
 */
public void ensureCapacity(int minCapacity) {
    //最小长度 如果数组不为空 最小即为0 否则为默认的10
    int minExpand = (elementData != EMPTY_ELEMENTDATA)
        // any size if real element table
        ? 0
        // larger than default for empty table. It's already supposed to be
        // at default size.
        : DEFAULT_CAPACITY;
    //如果需要的长度  即目标长度大于最小长度 说明需要扩容
    if (minCapacity > minExpand) {
        ensureExplicitCapacity(minCapacity);
    }
}

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);
}

/**
 * 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;
    //新集合的长度 是旧集合长度的 大概1.5倍
    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);
}

//附带下copy方法  
public static <T> T[] copyOf(T[] original, int newLength) {
    return (T[]) copyOf(original, newLength, original.getClass());
}


public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
    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;
}


其实扩容也就在grow()方法中的几行代码 主要是对集合长度的控制。

大精华之二 Iterator:
最常见的listIterator()方法

 /**
 * Returns a list iterator over the elements in this list (in proper
 * sequence), starting at the specified position in the list.
 * The specified index indicates the first element that would be
 * returned by an initial call to {@link ListIterator#next next}.
 * An initial call to {@link ListIterator#previous previous} would
 * return the element with the specified index minus one.
 *
 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
 *
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public ListIterator<E> listIterator() {
    return listIterator(0);
}

public ListIterator<E> listIterator(final int index) {
    rangeCheckForAdd(index);

    return new ListItr(index);
}

ListItr是个什么鬼?原来是一个内部类,实现了ListIterator接口

private class ListItr extends Itr implements ListIterator<E> {
    //把坐标传递进来
    ListItr(int index) {
        cursor = index;
    }

    public boolean hasPrevious() {
        return cursor != 0;
    }

    public E previous() {
        checkForComodification();
        try {
            int i = cursor - 1;
            E previous = get(i);
            lastRet = cursor = i;
            return previous;
        } catch (IndexOutOfBoundsException e) {
            checkForComodification();
            throw new NoSuchElementException();
        }
    }

    public int nextIndex() {
        return cursor;
    }

    public int previousIndex() {
        return cursor-1;
    }

    public void set(E e) {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            AbstractList.this.set(lastRet, e);
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    public void add(E e) {
        checkForComodification();

        try {
            int i = cursor;
            AbstractList.this.add(i, e);
            lastRet = -1;
            cursor = i + 1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }
}

//看完之后你会发现确实没什么东西 但是Iterator这个东西在很多地方都有用到,这里就显现出来接口的强大之处。

总结

看完ArrayList的源码之后,对ArrayList数据存储有了更深的理解,然而它的性能如何呢,要知道扩容和写数据都是需要时间的,经过测试,ArrayList在遍历和普通插入(add(object))的性能上都优于LinkedList。但是LinkedList在首尾进行操作的性能上明显优于ArrayList.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 内容概要 《计算机试卷1》是一份综合性的计算机基础和应用测试卷,涵盖了计算机硬件、软件、操作系统、网络、多媒体技术等多个领域的知识点。试卷包括单选题和操作应用两大类,单选题部分测试学生对计算机基础知识的掌握,操作应用部分则评估学生对计算机应用软件的实际操作能力。 ### 适用人群 本试卷适用于: - 计算机专业或信息技术相关专业的学生,用于课程学习或考试复习。 - 准备计算机等级考试或职业资格认证的人士,作为实战演练材料。 - 对计算机操作有兴趣的自学者,用于提升个人计算机应用技能。 - 计算机基础教育工作者,作为教学资源或出题参考。 ### 使用场景及目标 1. **学习评估**:作为学校或教育机构对学生计算机基础知识和应用技能的评估工具。 2. **自学测试**:供个人自学者检验自己对计算机知识的掌握程度和操作熟练度。 3. **职业发展**:帮助职场人士通过实际操作练习,提升计算机应用能力,增强工作竞争力。 4. **教学资源**:教师可以用于课堂教学,作为教学内容的补充或学生的课后练习。 5. **竞赛准备**:适合准备计算机相关竞赛的学生,作为强化训练和技能检测的材料。 试卷的目标是通过系统性的题目设计,帮助学生全面复习和巩固计算机基础知识,同时通过实际操作题目,提高学生解决实际问题的能力。通过本试卷的学习与练习,学生将能够更加深入地理解计算机的工作原理,掌握常用软件的使用方法,为未来的学术或职业生涯打下坚实的基础。
### 内容概要 这份《计算机试卷1》包含多个部分,主要覆盖了计算机基础知识、操作系统应用、文字处理、电子表格、演示文稿制作、互联网应用以及计算机多媒体技术。试卷以单选题开始,涉及计算机历史、基本概念、硬件组成、软件系统、网络协议等。接着是操作应用部分,要求考生在给定的软件环境中完成一系列具体的计算机操作任务。 ### 适用人群 本试卷适用于计算机科学与技术、信息技术相关专业的学生,以及准备计算机水平考试或职业资格认证的人士。它适合那些希望检验和提升自己计算机操作能力的学习者,也适用于教育工作者作为教学评估工具。 ### 使用场景及目标 1. **学习评估**:作为教育机构的课程评估工具,帮助教师了解学生对计算机基础知识的掌握程度。 2. **自学检验**:供个人自学者检验自己的计算机操作技能和理论知识,为进一步学习提供方向。 3. **职业发展**:为职场人士提供计算机技能的自我提升途径,增强其在信息时代的竞争力。 4. **考试准备**:为准备计算机相关考试的考生提供实战演练的机会,加强考试自信。 5. **教学资源**:教师可以将其作为教学资源,设计课程和实验,提高教学效果。 试卷的目标是通过理论知识的测试和实践技能的操作,全面提升考生的计算机应用能力。考生应掌握从基础的计算机组成原理到复杂的数据处理、演示文稿制作、网络应用以及多媒体技术处理等多方面技能。通过本试卷的学习与练习,考生将能够更加熟练地使用计算机解决实际问题,为未来的学术或职业生涯打下坚实的基础。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值