Java ArrayListコンストラクション関数ソース分析

2405 ワード

1.ArrayListは、下位レベルでObject[]を維持します.汎用を使用している場合は、汎用指定タイプの配列オブジェクトを維持します.
    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer.
     */
    private transient E[] elementData;

ArrayListがメンテナンスする配列の長さは「容量」を表し、ユーザーは一般的に「容量」という値を自発的にメンテナンスしません.私たちが一般的に使用するのは配列の長さ、つまりあなたがどれだけのオブジェクトをaddしたかです.
2.ユーザがArrayListオブジェクトのsize()メソッドによりArrayListインスタンス中のオブジェクトの数を得る
/**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

 
/**
     * Returns the number of elements in this list.
     *
     * @return  the number of elements in this list.
     */
    public int size() {
	return size;
    }

add removeなどの操作を行うと、ArrayListオブジェクトはsize値を自動的に維持します
3.ArrayListの構成方法
(1)「容量」の構成方法を指定する
/**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param   initialCapacity   the initial capacity of the list.
     * @exception IllegalArgumentException if the specified initial capacity
     *            is negative
     */
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
	this.elementData = (E[])new Object[initialCapacity];
    }

ArrayListクラスをインスタンス化するときに「容量」を指定すると、ArrayListは指定された容量サイズの配列を生成します
(2)デフォルトの構築方法
    
/**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
	this(10);
    }

(3)指定した集合内容と同じArrayListを作成する
    
/**
     * @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) {
        size = c.size();
        // Allow 10% room for growth
        int capacity = (int) Math.min((size*110L)/100, Integer.MAX_VALUE);
        elementData = (E[]) c.toArray(new Object[capacity]);
    }

この構造法を用いて生成されたオブジェクトは,パラメータCollection extends E>cのhashCode値と同じであるが,両者は互いに影響しない.
このとき、ArrayListインスタンスの「容量」は、パラメータCollection extends E>cのsize(必ずsizeであり、cの「容量」ではないことに注意)の110%+1である