其他分享
首页 > 其他分享> > ArrayList扩容机制,简单介绍

ArrayList扩容机制,简单介绍

作者:互联网

ArrayList

初始化:

  1. 如果调用空构造方法,默认elementData为10;

  2. 扩容倍数为1.5倍 oldCapacity +oldCapacity >>1 //oldCapacity =10

  3. 可以指定大小,如果指定大小以后,oldCapacity 为设置的大小

>>1表示除以2

新建arraylist,无参初始化:(先走classloader和hashcode,不做记录)

public ArrayList() {
   this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
public synchronized boolean add(E e) {
   modCount++;
   ensureCapacityHelper(elementCount + 1);
   elementData[elementCount++] = e;
   return true;
}
private void ensureCapacityHelper(int minCapacity) {
   // overflow-conscious code
   if (minCapacity - elementData.length > 0)
       grow(minCapacity);
}

如果elmentcount+1 -数组长度 >0,也就是下一个元素将会越界时候,进行扩容

public synchronized boolean add(E e) {
   modCount++;
   ensureCapacityHelper(elementCount + 1);
   elementData[elementCount++] = e;
   return true;
}

赋值。

看看添加第一个元素结果:

arrayList.add(101);
public static Integer valueOf(int i) {
   if (i >= IntegerCache.low && i <= IntegerCache.high)
       return IntegerCache.cache[i + (-IntegerCache.low)];
   return new Integer(i);
}

先转型成Integer

public boolean add(E e) {
   ensureCapacityInternal(size + 1);  // Increments modCount!!
   elementData[size++] = e;
   return true;
}

一样会先判断是否需要扩容,

private void ensureCapacityInternal(int minCapacity) {
   ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
   if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
       return Math.max(DEFAULT_CAPACITY, minCapacity);
  }
   return minCapacity;
}

计算,此处DEFAULTCAPACITY_EMPTY_ELEMENTDATA ={}

private void ensureCapacityInternal(int minCapacity) {
   ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
   modCount++;

   // overflow-conscious code
   if (minCapacity - elementData.length > 0)
       grow(minCapacity);
}

此处minCapacity为10,elementData.length为0,所以需要扩容

private void grow(int minCapacity) {
   // overflow-conscious code
   int oldCapacity = elementData.length;
   int newCapacity = oldCapacity + (oldCapacity >> 1);
   if (newCapacity - minCapacity < 0)
       newCapacity = minCapacity;
   if (newCapacity - MAX_ARRAY_SIZE > 0)
       newCapacity = hugeCapacity(minCapacity);
   // minCapacity is usually close to size, so this is a win:
   elementData = Arrays.copyOf(elementData, newCapacity);
}

本质就是copy一个新数组

public static <T> T[] copyOf(T[] original, int newLength) {
   return (T[]) copyOf(original, newLength, original.getClass());
}

扩容完成后返回,将值写入新数组,over

public boolean add(E e) {
   ensureCapacityInternal(size + 1);  // Increments modCount!!
   elementData[size++] = e;
   return true;
}

 

标签:扩容,return,int,ArrayList,elementData,minCapacity,oldCapacity,机制,public
来源: https://www.cnblogs.com/minejava/p/14902695.html