LoginSignup
2
3

More than 3 years have passed since last update.

【Java】ArrayListの正体

Last updated at Posted at 2020-04-29

ArrayListの宣言・初期化方法

ArrayListは以下のように宣言する。
ArrayList<型> 変数名 = new ArrayList<型>(初期容量); ※初期容量は省略可

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

なぜプリミティブ型はだめなのか

ArrayListの中身を見てみる

ArrayList.class
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

初期容量は何のために指定するのか

new、add、get、removeしたときに起きていること

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

配列の移動がどれほど影響あるか

指定しない場合

ArrayListSample.java
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");

結果

処理時間:6505 ms

指定した場合

ArrayListSample.java
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秒ほどの差が出た。

結論

大容量の場合、想定する容量を指定しておく

2
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3