public synchronized boolean add(E e)方法源码

public class Vector<E>
	extends AbstractList<E>
	implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{

		// 空数组
		protected Object[] elementData;

		// 当前数组元素个数
		protected int elementCount;

   
		// 自定义扩容个数
		protected int capacityIncrement;

		// 初始化构造方法1
		public Vector() {
			this(10);
		}
		
		// 初始化构造方法2
		public Vector(int initialCapacity) {
			this(initialCapacity, 0);
		}
		
		// 初始化构造方3
		public Vector(int initialCapacity, int capacityIncrement) {
			super();
			if (initialCapacity < 0)
				throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);
				
			this.elementData = new Object[initialCapacity]; // 自定义一个容量为10的数组
			this.capacityIncrement = capacityIncrement; // 指定扩容的容量
		}		
		
		// 添加方法
		public synchronized boolean add(E e) {
			modCount++;
			ensureCapacityHelper(elementCount + 1);
			elementData[elementCount++] = e;
			return true;
		}
		
		// 检验是否需要进行扩容
		private void ensureCapacityHelper(int minCapacity) {
			//判断当前数组容量是否足以存储第minCapacity个元素	
			if (minCapacity - elementData.length > 0) 
					grow(minCapacity);
		}
		
		// 扩容操作
		private void grow(int minCapacity) {
			// 若没有指定自定义的容量,则以2倍的oldCapacity【默认为10】进行扩容;
			// 否则以oldCapacity【默认为10】 + capacityIncrement进行扩容
			int oldCapacity = elementData.length;
			int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
											 capacityIncrement : oldCapacity);
			if (newCapacity - minCapacity < 0)
				newCapacity = minCapacity;
			if (newCapacity - MAX_ARRAY_SIZE > 0)
				newCapacity = hugeCapacity(minCapacity);
			elementData = Arrays.copyOf(elementData, newCapacity);
		}
}

public class Main {
	public static void main(String[] args) {
		Vector<Integer> vector = new Vector<>();
		for (int i = 0; i < 11; i++){
			vector.add(i);
		}
	}
}
posted @ 2024-04-30 23:55  jock_javaEE  阅读(7)  评论(0编辑  收藏  举报