ArayListソースコード探究(一)ArayList容量

2848 ワード

ArayListソースコード探究(一)ArayList容量
ArayListが実際に維持されているのは、ElemenntDataという配列であり、Elementa.lengthは配列の実際の容量(メモリ空間を占める)であり、ArayListのインスタンスのsize属性は要素の数だけを特徴づける。ArayListには二つのコンストラクタがあります。一つは無パラメータのコンストラクタ、もう一つはパラメータのあるコンストラクタです。
import java.util.ArrayList;
import java.util.Iterator;

public class     {   
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		/*       */
		ArrayList a = new ArrayList(0);
		System.out.println(a.size());          //  0
		System.out.println(a.get(0));         //    ,      
	}
}
参画の構造関数のソースコード
public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {    //     0 ,            
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {   //    0 ,   {} ,   
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
無参の構造関数のソースコード
public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
容量増加:1:無参構造方法
import java.lang.reflect.*;
import java.util.ArrayList;

public class     {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		
		ArrayList a = new ArrayList();//         

		Field f1 = ArrayList.class.getDeclaredField("elementData");   //          
		f1.setAccessible(true);
		Object[] elementData;
		
		for(int i=0;i<50;i++){
			a.add(i);
			elementData = (Object[])f1.get(a);
			System.out.print(elementData.length+"\\");  //             
		}
		
	}
}

出力は10\10\10\10\10\10\10\10\10\10\10\10\15\15\15\15\15\15\22\22\22\22\22\22\22\22\33\33\33\33\33\33\33\33\49\49\49\49\49\49\49\49\49\49\49\49\49\49\49\49\49\49\49\49\49\49\49\49\49\49のソースのサイズを変更できます。
2パラメータの構造方法があります。
import java.lang.reflect.*;
import java.util.ArrayList;

public class     {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		
		ArrayList a = new ArrayList(18);//         

		Field f1 = ArrayList.class.getDeclaredField("elementData");   //          
		f1.setAccessible(true);
		Object[] elementData;
		
		for(int i=0;i<50;i++){
			a.add(i);
			elementData = (Object[])f1.get(a);
			System.out.print(elementData.length+"\\");  //             
		}
		
	}
}
出力は18\18\18\18\18\18\18\18\18\18\18\18\18\18\18\18\18\18\18\18\18\18\27\27\27\27\27\27\27\40\40\40\40\40\40\40\40\40\40\40\40\40\40\40\40\60\60\60\60\60\60\60\60\60\60\60\60\60\60\60\60\60\60\60\60\60\60\60\60\60を超える場合と同じように、拡充規則を超えます。