ArrayList就是传说中的动态数组,就是数组的封装实现,它提供了动态的增加和减少元素,灵活的设置数组的大小等好处,主要实现了Collection,Iterable,RandomAccess(修饰接口,表明这个类可以随机访问)等。
ArrayList提供了3种构造方法:
1.可以构造一个指定容量大小的ArrayList对象
1 /** 2 * Constructs an empty list with the specified initial capacity. 3 * 4 * @param initialCapacity the initial capacity of the list 5 * @throws IllegalArgumentException if the specified initial capacity 6 * is negative 7 */ 8 public ArrayList(int initialCapacity) { 9 super(); 10 if (initialCapacity < 0) 11 throw new IllegalArgumentException("Illegal Capacity: "+ 12 initialCapacity); 13 this.elementData = new Object[initialCapacity]; 14 }
2.构造一个默认大小的ArrayList对象,
1 /** 2 * Constructs an empty list with an initial capacity of ten. 3 */ 4 public ArrayList() { 5 super(); 6 this.elementData = EMPTY_ELEMENTDATA; 7 }
/**
* The array buffer into which the elements of the ArrayList are
stored.
* The capacity of the ArrayList is the length of this array
buffer. Any
* empty ArrayList with elementData == EMPTY_ELEMENTDATA will
be expanded to
* DEFAULT_CAPACITY when the first element is added.
*/
private transient Object[] elementData;
当第一次add的时候 如果elementData == EMPTY_ELEMENTDATA,将会最小扩充到DEFAULT_CAPACITY = 10
3.构造一个包含某个Collection容器中所有对象的ArrayList对象
1 /** 2 * Constructs a list containing the elements of the specified 3 * collection, in the order they are returned by the collection‘s 4 * iterator. 5 * 6 * @param c the collection whose elements are to be placed into this list 7 * @throws NullPointerException if the specified collection is null 8 */ 9 public ArrayList(Collection<? extends E> c) { 10 elementData = c.toArray(); 11 size = elementData.length; 12 // c.toArray might (incorrectly) not return Object[] (see 6260652) 13 if (elementData.getClass() != Object[].class) 14 elementData = Arrays.copyOf(elementData, size, Object[].class); 15 }
注意
// c.toArray might (incorrectly) not return Object[] (see 6260652)
返回若不是Object[]将调用 Arrays.copyOf方法将其转为Object[].
如下demo:
1 public class Test { 2 public static void main(String[] args) { 3 List<Object> l = new ArrayList<Object>(Arrays.asList("foo", "bar")); 4 Object[] obj; 5 obj = Arrays.asList("foo", "bar").toArray(); 6 // Arrays.asList("foo", "bar").toArray() produces String[], 7 System.out.println(obj.getClass().getName());//实际是String[]对象 8 obj = Arrays.copyOf(obj, obj.length, Object[].class);//转成Object[]对象 9 System.out.println(obj.getClass().getName()); 10 l.set(0, new Object()); // Causes ArrayStoreException 11 } 12 }
浅谈Java中的ArrayList类,布布扣,bubuko.com
原文:http://www.cnblogs.com/yyrookie/p/3586256.html