image.png
    ArrayList 实现了Iterable,RandomAccess,Collection,List,Cloneable接口,其中RandomAccess,Cloneable 和Serializable是标记接口,表明实现随机访问,可克隆以及序列化
    ArrayList里主要的几个变量

    1. //默认初始化大小
    2. private static final int DEFAULT_CAPACITY = 10;
    3. //用于空实例的共享数组实例
    4. private static final Object[] EMPTY_ELEMENTDATA = {};
    5. //用于默认大小的空实例的共享空数组实例
    6. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    7. //储存ArrayList元素的缓冲区
    8. transient Object[] elementData;
    9. //ArrayList包含的元素个数
    10. private int size;
    11. //最大容量
    12. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    13. protected transient int modCount = 0;
    14. //最常用构造函数,构造一个初始化容量为10的数组
    15. public ArrayList() {
    16. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    17. }
    18. //调用add方法来向list中添加元素
    19. public boolean add(E e) {
    20. //判断当前容量是否放的下新增元素,容量够就不变,容量不够扩容
    21. ensureCapacityInternal(size + 1); // Increments modCount!!
    22. //
    23. elementData[size++] = e;
    24. return true;
    25. }
    26. private void ensureCapacityInternal(int minCapacity) {
    27. ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    28. }
    29. private static int calculateCapacity(Object[] elementData, int minCapacity) {
    30. //首次添加元素时,elementData中没东西,if表达式为true, minCapacity=1
    31. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
    32. //此处直接返回DEFAULT_CAPACITY = 10
    33. return Math.max(DEFAULT_CAPACITY, minCapacity);
    34. }
    35. return minCapacity;
    36. }
    37. private void ensureExplicitCapacity(int minCapacity) {
    38. //modCount 继承自AbstractList 用于记录list结构修改的次数,即容量改变的次数,容量改变一次此处加一
    39. modCount++;
    40. //首次进入minCapacity为10,if 表达式为true
    41. // overflow-conscious code
    42. if (minCapacity - elementData.length > 0)
    43. grow(minCapacity);
    44. }
    45. private void grow(int minCapacity) {
    46. // overflow-conscious code
    47. //首次oldCapacity = 0,minCapacity
    48. int oldCapacity = elementData.length;
    49. //oldCapacity >> 1,右位移运算符 num >> 1,相当于num除以2,所以此处首次仍然为0,newCapacity = minCapacity = 10;复制elementData中1-10个元素到elementData中
    50. int newCapacity = oldCapacity + (oldCapacity >> 1);
    51. if (newCapacity - minCapacity < 0)
    52. newCapacity = minCapacity;
    53. if (newCapacity - MAX_ARRAY_SIZE > 0)
    54. newCapacity = hugeCapacity(minCapacity);
    55. // minCapacity is usually close to size, so this is a win:
    56. elementData = Arrays.copyOf(elementData, newCapacity);
    57. }