【Java】ArrayList的真相

数组列表的声明和初始化方法

ArrayList的声明如下:
ArrayList<类型> 变量名 = new ArrayList<类型>(初始容量); ※初始容量可省略

ArrayList<Integer> arrayList = new ArrayList<Integer>();  //  初期容量指定しない
ArrayList<Integer> arrayList = new ArrayList<Integer>(3); //  初期容量指定する
//ArrayList<int> arrayList = new ArrayList<int>();        //  コンパイルエラー

为什么原始类型不好?

让我们看看ArrayList中的内容

public class ArrayList<E> extends AbstractList<E> … {
    private static final int DEFAULT_CAPACITY = 10;
    private static final Object[] EMPTY_ELEMENTDATA = {};
    transient Object[] elementData;      // ← ArrayListデータの実態
    private int size;
    //コンストラクタ
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
//中略

ArrayList的本质是以Object[]为核心的一个方便操作的类。
只能将Object类型的数据类型用作ArrayList。
原生类型不是继承自Object类型的数据类型,所以无法使用。

基本类型

//8種類
byte, short, boolean, char, int, long, float, double

为什么要指定初始容量?

每当进行新建、添加、获取和删除操作时发生的事情。

ArrayList<Integer> arrayList = new ArrayList<Integer>(3);
arrayList.add(new Integer(10); //a
arrayList.add(new Integer(11); //b
arrayList.add(new Integer(12); //c
arrayList.get(1);
arrayList.remove(1);
new.png

如果超出了初始容量所能容纳的元素数量

ArrayList<Integer> arrayList = new ArrayList<Integer>(3);
arrayList.add(new Integer(10); //a
arrayList.add(new Integer(11); //b
arrayList.add(new Integer(12); //c
arrayList.add(new Integer(13); //d
new.png

移動数组会有多大的影响。

如果没有指定的话

ArrayList<Integer> arrayList = new ArrayList<Integer>();
long array1Start = System.currentTimeMillis();
for(int i=0; i < 10000000;i++) {              // ← 1000万
    arrayList.add(new Integer(10));
}
long array1End = System.currentTimeMillis();
System.out.println("処理時間:" + (array1End - array1Start) + " ms");

结果 (jié guǒ)

処理時間:6505 ms

如果指定的话

ArrayList<Integer> arrayList = new ArrayList<Integer>(10000000);
long array1Start = System.currentTimeMillis();
for(int i=0; i < 10000000;i++) {               // ← 1000万
    arrayList.add(new Integer(10));
}
long array1End = System.currentTimeMillis();
System.out.println("処理時間:" + (array1End - array1Start) + " ms");

结果
成果
效果

処理時間:5630 ms

出现了大约1秒的时间差。

结论 (jié

如果容量很大,請指定預期的容量。

广告
将在 10 秒后关闭
bannerAds