首页 > 编程语言 > 详细

Java ArrayList构造分析

时间:2016-01-19 15:46:39      阅读:177      评论:0      收藏:0      [点我收藏+]

 

 1 /** 
 2       * The array buffer into which the elements of the ArrayList are stored. 
 3       * The capacity of the ArrayList is the length of this array buffer. 
 4       */  
 5      private transient Object[] elementData;  
 6    
 7      /** 
 8       * The size of the ArrayList (the number of elements it contains). 
 9       * 
10       * @serial 
11       */  
12      private int size;  

从这里看出, ArrayList是用Array来实现的,包括elementData数组和其大小两个属性。

 

1 public boolean add(E e) {  
2     ensureCapacity(size + 1);  // Increments modCount!!  
3     elementData[size++] = e;  
4     return true;  
5 }  
/** 
      * Increases the capacity of this <tt>ArrayList</tt> instance, if 
      * necessary, to ensure that it can hold at least the number of elements 
      * specified by the minimum capacity argument. 
      * 
      * @param   minCapacity   the desired minimum capacity 
      */  
     public void ensureCapacity(int minCapacity) {  
     modCount++;  
     int oldCapacity = elementData.length;  
     if (minCapacity > oldCapacity) {  
         Object oldData[] = elementData;  
         int newCapacity = (oldCapacity * 3)/2 + 1;  
             if (newCapacity < minCapacity)  
         newCapacity = minCapacity;  
             // minCapacity is usually close to size, so this is a win:  
             elementData = Arrays.copyOf(elementData, newCapacity);  
     }  
     }  

ensureCapacity ensure that the inner array size satisfy the add(Object o) operation. If minCapacity is bigger than the original array size, it increase the array size and do the checking again. ensureCapacity() will increase the array size by at least 1. After the array size is OK, copy original array into new array with bigger size. After ensureCapacity() is returned, set elementData[size] to be the newly added element. Since the array size is increased by at least one. call elementData[size] will not throw exception.

 

Java ArrayList构造分析

原文:http://www.cnblogs.com/touchdown/p/5142286.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!