常用集合-ArrayList
一 查看源码ArrayList类
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
其继承于AbstractList;实现了List 接口,RandomAccess 接口, Cloneable 接口,java.io.Serializable接口;
1 实现Serializable接口表示其可以序列化;支持远程传输调用;
2 实现Cloneable 接口表示其可复制;
/** * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The * elements themselves are not copied.) * * @return a clone of this <tt>ArrayList</tt> instance */ public Object clone() { try { ArrayList<?> v = (ArrayList<?>) super.clone(); v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(e); } }
这是其复制实现:因为Object.clone();仅仅是对象的引用地址复制;在这里其将元素内容复制了一份;实现源对象和复制对象改动互不影响;
3 实现RandomAccess 接口表示其支持快速随机访问;
4 实现List 接口
二 源码分析
/** * Default initial capacity. */ private static final int DEFAULT_CAPACITY = 10; /** * Shared empty array instance used for empty instances. */ private static final Object[] EMPTY_ELEMENTDATA = {}; /** * Shared empty array instance used for default sized empty instances. We * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when * first element is added. */ private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
1 DEFAULT_CAPACITY = 10; 缺省的初始化容量;当首次调用add方法时容量初始化为10;
2 EMPTY_ELEMENTDATA ;空数组;当调用有参数构造函数时;如果初始化容量为0 则 容器为其;
3 DEFAULTCAPACITY_EMPTY_ELEMENTDATA ;空数组;当调用无参构造函数时;容器为其;
/** * 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 == DEFAULTCAPACITY_EMPTY_ELEMENTDATA * will be expanded to DEFAULT_CAPACITY when the first element is added. */ transient Object[] elementData; // non-private to simplify nested class access /** * The size of the ArrayList (the number of elements it contains). * * @serial */ private int size;
4 elementData 这个字段表示实际存储的内容,其支持快速的随机访问的原理也由此产生;
5 size 这个字段表示实际存储的数量;
浙公网安备 33010602011771号