1. 简介 Vector跟ArrayList一样是一个基于数组实现的List,只不过Vector是线程安全的,在可能出现线程安全性问题的方法,Vector都加上了关键字synchronized
。 与ArrayList一样,Vector查找元素的时间复杂度是O(1),插入删除时间复杂度为O(n)。
2. 实现 属性 1 2 3 4 5 6 7 8 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8 ;protected Object[] elementData;protected int elementCount;protected int capacityIncrement;
构造函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public Vector (int initialCapacity, int capacityIncrement) { super (); if (initialCapacity < 0 ) throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); this .elementData = new Object[initialCapacity]; this .capacityIncrement = capacityIncrement; } public Vector (int initialCapacity) { this (initialCapacity, 0 ); } public Vector () { this (10 ); }
扩容函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 private void ensureCapacityHelper (int minCapacity) { if (minCapacity - elementData.length > 0 ) grow(minCapacity); } private void grow (int minCapacity) { 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); }
增删改查方法 Vector在这些方法的实现上与ArrayList基本一致,但为保证线程安全所以在所有可能出现线程安全问题的方法一律加上synchronized
关键字,这在非多线程下使用效率不及ArrayList高,而要想要高效的使用 线程安全的List,CopyOnWriteArrayList
是一个更好的选择。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 E elementData (int index) { return (E) elementData[index]; } public synchronized E get (int index) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); return elementData(index); } public synchronized E set (int index, E element) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } public synchronized boolean add (E e) { modCount++; ensureCapacityHelper(elementCount + 1 ); elementData[elementCount++] = e; return true ; } public synchronized E remove (int index) { modCount++; if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); E oldValue = elementData(index); int numMoved = elementCount - index - 1 ; if (numMoved > 0 ) System.arraycopy(elementData, index+1 , elementData, index, numMoved); elementData[--elementCount] = null ; return oldValue; }
最后更新时间:2018-04-15 12:19:23