我想要看ArrayList的真正容积,但是正真容积不能从他的size得到,
所以这里我使用反射得到他的私有域“elementData”,elementData的大小就是ArrayList的实际大小了。
1 public static void testCapasity(){ 2 //看看我先把ArrayList增大,看看如果我把元素减少会不会他也会自动将空间缩小 3 try{ 4 ArrayList<Integer> array = new ArrayList<Integer>(); 5 Class clazz = array.getClass(); 6 Field field =clazz.getDeclaredField("elementData"); 7 field.setAccessible(true); 8 Object obj ; 9 10 obj = field.get(array); 11 System.out.println("before init "+Array.getLength(obj)); 12 13 for(int i = 0;i<100;i++){ 14 array.add(i); 15 } 16 17 System.out.println(" after added size is "+array.size()); 18 19 obj = field.get(array); 20 System.out.println("after added "+Array.getLength(obj)); 21 22 array.clear(); 23 24 System.out.println(" after removed size is "+array.size()); 25 obj = field.get(array); 26 System.out.println("after removed "+Array.getLength(obj)); 27 28 }catch(NoSuchFieldException e){ 29 e.printStackTrace(); 30 }catch (IllegalAccessException e){ 31 e.printStackTrace(); 32 } 33 34 }
输出的结果是:
before init 0 after added size is 100 after added 109 after removed size is 0 after removed 109 Process finished with exit code 0
所以由这里看出来ArrayList不会自动缩小容积,那么如果我们需要缩小容积怎么办呢?
其实ArrayList里面有一个方法可以缩小容积
/** * Trims the capacity of this <tt>ArrayList</tt> instance to be the * list's current size. An application can use this operation to minimize * the storage of an <tt>ArrayList</tt> instance. */ public void trimToSize() { modCount++; if (size < elementData.length) { elementData = Arrays.copyOf(elementData, size); } }
所以我们在增加了容积之后可以使用这个方法来缩小不需要的容积。