Java ArrayList 源码分析


ArrayList

  • 当处理确定长度的大量数据时,如果数据更多的只是用来浏览,那么可以使用 ArrayList 来记录数据或数据索引位置,这样虽然增删慢但是查找元素变得很快。
  • 原因是因为 ArrayList 的底层是数组实现的,那么具体是怎会实现的呢?

1. API 中的变量

	private static final long serialVersionUID = 8683452581122892189L;

    /**
     * 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.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;
类型 变量 说明
long DEFAULT_CAPACITY 初始默认变量,设定为10
int[] EMPTY_ELEMENTDATA 给空对象使用的数组
Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA 给指定了大小的对象使用的数组
Object[] elementData 给其他非空对象使用的数组
  • 细心的人就会发现了,除了最重要的非空数组 elementData 是 default 修饰词,其他的变量都是 private 修饰的,在 elementData 后面注释的 non-private to simplify nested class access 是指默认访问权限可以简化嵌套类访问过程,又是什么意思呢?

a. 默认访问权限为什么可以简化嵌套类访问过程?

i. 什么是嵌套类?

  • 在 Java 语言中允许在另外一个类中定义一个类,这样的类被称为嵌套类(Nested Class),包含嵌套类的类称为外部类(Outer Class),也可以叫做封闭类,详见:Java 的内部类
  • 嵌套类分为两类:
  • 静态嵌套类(Static Nested Classes):使用 static 声明,一般称为 嵌套类(Nested Classes)
  • 非静态嵌套类(Non-static Nested Classes ):非 static 声明,一般称为内部类(Inner Classes);
class OuterClass {
    //外部类
    static class StaticNestedClass {
        //嵌套类
    }

    class InnerClass {
        //内部类
    }
}
  • 嵌套类作为外部类的一个成员,可以被声明为 private public protected 或者包范围(即 default),而外部类只能被声明为 public 或者包范围,详见:Java 的权限修饰符
  • 嵌套类是它的外部类的成员,非静态嵌套类(内部类)可以访问外部类的其他成员,而静态嵌套类只能访问外部类的静态成员,包括静态私有成员和静态非私有成员;

ii. 嵌套类的访问过程是怎样的?

  • 内部类在编译时是独立的一个类,类名为 外部类$内部类(根据 Java 语言规范 ,$ 只用在生成的代码中,或者用来访问历史遗留系统中的预置名称),并且与外部类处于同一个包下,如前文所说,外部类只能被声明为 public 或者包范围,所以内部类可以访问到外部类;
  • 下面比较一下内部类访问外部类的私有与非私有方法,先确定实验代码块:
public class Test {
    private int test;
    //int test;
    
    class Inner {
        void access() {
            System.out.println(test);
        }
    }

    public static void main(String[] args) {
        new Test().new Inner().access();
    }
}
  • 通过代码对比工具 Diffchecker 对比不同的 Test$Inner.class 发现,含有 private 的字节码文件多了一个域,这个域其实是一个静态的访问方法,用于获取 private 修饰的变量 test,内部类通过访问外部类中的这个静态方法来实现访问私有字段的目的;
  • 由此可见,在访问私有变量时,编译器需要在外部类中生成静态访问方法,同时也需要在内部类访问外部类字段时调用合成的方法;

iii. 总结

  • 原因简单来说就是非 private 修饰会简化内部类访问该字段的过程,以此来提高性能,当然也牺牲了一些安全性,这个原理设计到反编译到汇编级别的内容;

2. API 中的构造方法

    /**
     * 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
     */
    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 an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 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
     */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // defend against c.toArray (incorrectly) not returning Object[]
            // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
构造方法 说明
public ArrayList() 构造一个初始容量为10的空列表
public ArrayList(int initialCapacity) 构造一个指定初始容量的空列表
public ArrayList(Collection c) 构造一个包含指定集合元素的列表,按迭代器返回的顺序

3. API 中的主要方法

    /**
     * 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
     * @throws OutOfMemoryError if minCapacity is less than zero
     */
    private Object[] grow(int minCapacity) {
        int oldCapacity = elementData.length;
        if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            int newCapacity = ArraysSupport.newLength(oldCapacity,
                    minCapacity - oldCapacity, /* minimum growth */
                    oldCapacity >> 1           /* preferred growth */);
            return elementData = Arrays.copyOf(elementData, newCapacity);
        } else {
            return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
        }
    }

    private Object[] grow() {
        return grow(size + 1);
    }

    /**
     * Returns the number of elements in this list.
     *
     * @return the number of elements in this list
     */
    public int size() {
        return size;
    }
    
    /**
     * This helper method split out from add(E) to keep method
     * bytecode size under 35 (the -XX:MaxInlineSize default value),
     * which helps when add(E) is called in a C1-compiled loop.
     */
    private void add(E e, Object[] elementData, int s) {
        if (s == elementData.length)
            elementData = grow();
        elementData[s] = e;
        size = s + 1;
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        modCount++;
        add(e, elementData, size);
        return true;
    }
  • 每次用 add() 方法增加新元素时,如果长度够用,那么会直接插入的对应位置,否则会新创建一个最小的、满足条件的长度的数组;
  • 可见 ArrayList 本质就是增加了很多方法的数组;

4. 链接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章