Vector与ArrayList一样,也是通过数组实现的,不同的是它支持线程的同步,即某一时刻只有一个线程能够写Vector,避免多线程同时写而引起的不一致性,但实现同步需要很高的花费,因此,访问它比访问ArrayList慢。

什么是Vector

  1. Vector是矢量队列。它是jdk1.0版本添加的类 继承 AbstractList、实现 List, RandomAccess, Cloneable, java.io.Serializable 这些接口
  2. 继承 AbstractList,实现List.所有它是一个对队列。支持队列相关的操作
  3. Vector 实现 RandomAccess 所有提供随机访问功能,RandmoAccess是java中用来被List实现,为List提供快速访问功能的。在Vector中,我们即可以通过元素的序号快速获取元 素对象;这就是快速随机访问。
  4. Vector 实现了Cloneable接口,即实现clone()函数。它能被克隆。
  5. Vector 是线程安全的,但也导致了性能要低于ArrayList

    Vector继承关系图

    image.png

Vector源码解析

  1. package java.util;
  2. import java.io.IOException;
  3. import java.io.ObjectInputStream;
  4. import java.io.StreamCorruptedException;
  5. import java.util.function.Consumer;
  6. import java.util.function.Predicate;
  7. import java.util.function.UnaryOperator;
  8. public class Vector<E>
  9. extends AbstractList<E>
  10. implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  11. {
  12. //这就是存储数据的数组,注意啦这是一个动态的数组
  13. protected Object[] elementData;
  14. //当前元素的个数
  15. protected int elementCount;
  16. //容量增长系数,扩容时使用
  17. protected int capacityIncrement;
  18. // Vector的序列版本号
  19. private static final long serialVersionUID = -2767605614048989439L;
  20. //指定数组的初始化大小,和增长系数。容量不能小于0
  21. public Vector(int initialCapacity, int capacityIncrement) {
  22. super();
  23. if (initialCapacity < 0)
  24. throw new IllegalArgumentException("Illegal Capacity: "+
  25. initialCapacity);
  26. this.elementData = new Object[initialCapacity];
  27. this.capacityIncrement = capacityIncrement;
  28. }
  29. //指定容量,增长系数未 0
  30. public Vector(int initialCapacity) {
  31. this(initialCapacity, 0);
  32. }
  33. //采用默认 容量 10 增长系数为 0
  34. public Vector() {
  35. this(10);
  36. }
  37. //使用另一个集合构造改集合
  38. public Vector(Collection<? extends E> c) {
  39. elementData = c.toArray();
  40. elementCount = elementData.length;
  41. // c.toArray可能(错误地)不返回Object []
  42. if (elementData.getClass() != Object[].class)
  43. elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
  44. }
  45. //这时将Veector中的所有数据都拷贝到anArray中去
  46. public synchronized void copyInto(Object[] anArray) {
  47. System.arraycopy(elementData, 0, anArray, 0, elementCount);
  48. }
  49. //缩小当前数组的容量,为当前数组中元素的个数
  50. public synchronized void trimToSize() {
  51. modCount++;
  52. int oldCapacity = elementData.length;
  53. if (elementCount < oldCapacity) {
  54. //使用Arrays.copyOf方法将数据中的元素copy到新数组中
  55. elementData = Arrays.copyOf(elementData, elementCount);
  56. }
  57. }
  58. //如有必要,增加当前数组的容量,以确保至少可以保存minCapacity容量参数指定的元素个数
  59. public synchronized void ensureCapacity(int minCapacity) {
  60. if (minCapacity > 0) {
  61. modCount++;
  62. ensureCapacityHelper(minCapacity);
  63. }
  64. }
  65. /**
  66. * 和上面方法的功能一样,这么做的原因是这是一个内部使用的方法,使用就没有必要去同步,这样的好处就是可用
  67. * 降低同步所带来的开销
  68. */
  69. private void ensureCapacityHelper(int minCapacity) {
  70. if (minCapacity - elementData.length > 0)
  71. grow(minCapacity);
  72. }
  73. //当前数组的最大容量,其实扩容可用扩容到 Integer.MAX_VALUE往下面看就知道了
  74. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  75. //Vectory的扩容方法,嗯嗯看看它的扩容机制吧
  76. private void grow(int minCapacity) {
  77. int oldCapacity = elementData.length;
  78. //新的数组长度 = 旧数组长度 + 增长系数大于0加增长系数 否则 + 旧数组长度
  79. int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
  80. capacityIncrement : oldCapacity);
  81. //如果计算后还不够就 = 最小扩容数
  82. if (newCapacity - minCapacity < 0)
  83. newCapacity = minCapacity;
  84. //如果大于最大扩容数
  85. if (newCapacity - MAX_ARRAY_SIZE > 0)
  86. /**
  87. * hugeCapacity 返回 嗯嗯从这我们可用看错最大看扩容量位Integer.MAX_VALUE
  88. * (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE : MAX_ARRAY_SIZE;
  89. *
  90. */
  91. newCapacity = hugeCapacity(minCapacity);
  92. elementData = Arrays.copyOf(elementData, newCapacity);
  93. }
  94. private static int hugeCapacity(int minCapacity) {
  95. if (minCapacity < 0) // overflow
  96. throw new OutOfMemoryError();
  97. return (minCapacity > MAX_ARRAY_SIZE) ?
  98. Integer.MAX_VALUE :
  99. MAX_ARRAY_SIZE;
  100. }
  101. //设置当前数组的元素个数,如果小于当前元素的个数
  102. //那么就将多出来的元素置空,如果大于数组扩容
  103. public synchronized void setSize(int newSize) {
  104. modCount++;
  105. if (newSize > elementCount) {
  106. ensureCapacityHelper(newSize);
  107. } else {
  108. for (int i = newSize ; i < elementCount ; i++) {
  109. elementData[i] = null;
  110. }
  111. }
  112. elementCount = newSize;
  113. }
  114. //当前数组的大小
  115. public synchronized int capacity() {
  116. return elementData.length;
  117. }
  118. //元素个数
  119. public synchronized int size() {
  120. return elementCount;
  121. }
  122. //是否为空
  123. public synchronized boolean isEmpty() {
  124. return elementCount == 0;
  125. }
  126. //返回“Vector中全部元素对应的Enumeration(枚举)
  127. public Enumeration<E> elements() {
  128. //通过匿名类实现 Enumeration 接口
  129. return new Enumeration<E>() {
  130. int count = 0;
  131. public boolean hasMoreElements() {
  132. return count < elementCount;
  133. }
  134. public E nextElement() {
  135. synchronized (Vector.this) {
  136. if (count < elementCount) {
  137. return elementData(count++);
  138. }
  139. }
  140. throw new NoSuchElementException("Vector Enumeration");
  141. }
  142. };
  143. }
  144. //是否包含指定元素
  145. public boolean contains(Object o) {
  146. //从顶一位开始查找 通过 >= 0 判断是否包含
  147. return indexOf(o, 0) >= 0;
  148. }
  149. //返回指定元素在数组中的位置
  150. public int indexOf(Object o) {
  151. return indexOf(o, 0);
  152. }
  153. //指定元素 开始位置 返回改元素在数组中的下标
  154. public synchronized int indexOf(Object o, int index) {
  155. //判断以下是否位空,为空 用 == 不位空用 equals
  156. if (o == null) {
  157. //循环查找,找到返回
  158. for (int i = index ; i < elementCount ; i++)
  159. if (elementData[i]==null)
  160. return i;
  161. } else {
  162. for (int i = index ; i < elementCount ; i++)
  163. if (o.equals(elementData[i]))
  164. return i;
  165. }
  166. //如果每找到返回状态码 -1
  167. return -1;
  168. }
  169. //重后往前找,元素在数组中的位置。重最后一个元素开始找起
  170. public synchronized int lastIndexOf(Object o) {
  171. return lastIndexOf(o, elementCount-1);
  172. }
  173. //指定查找元素和查找起始位置。从后往前找
  174. public synchronized int lastIndexOf(Object o, int index) {
  175. if (index >= elementCount)
  176. throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
  177. if (o == null) {
  178. //就是倒着循环判断
  179. for (int i = index; i >= 0; i--)
  180. if (elementData[i]==null)
  181. return i;
  182. } else {
  183. for (int i = index; i >= 0; i--)
  184. if (o.equals(elementData[i]))
  185. return i;
  186. }
  187. //找不到一样返回状态码 -1
  188. return -1;
  189. }
  190. //返回指定下标处的元素
  191. public synchronized E elementAt(int index) {
  192. if (index >= elementCount) {
  193. throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
  194. }
  195. return elementData(index);
  196. }
  197. //返回第一个元素
  198. public synchronized E firstElement() {
  199. if (elementCount == 0) {
  200. throw new NoSuchElementException();
  201. }
  202. return elementData(0);
  203. }
  204. //返回最后一个元素
  205. public synchronized E lastElement() {
  206. if (elementCount == 0) {
  207. throw new NoSuchElementException();
  208. }
  209. return elementData(elementCount - 1);
  210. }
  211. //修改指定位置的元素
  212. public synchronized void setElementAt(E obj, int index) {
  213. if (index >= elementCount) {
  214. throw new ArrayIndexOutOfBoundsException(index + " >= " +
  215. elementCount);
  216. }
  217. elementData[index] = obj;
  218. }
  219. //移除指定位置的元素
  220. public synchronized void removeElementAt(int index) {
  221. modCount++;
  222. if (index >= elementCount) {
  223. throw new ArrayIndexOutOfBoundsException(index + " >= " +
  224. elementCount);
  225. }
  226. else if (index < 0) {
  227. throw new ArrayIndexOutOfBoundsException(index);
  228. }
  229. //j 是删除元素在数组中的位置
  230. int j = elementCount - index - 1;
  231. if (j > 0) {
  232. //移动数组位置:新数组位置 = 原数组移除元素的后一位都通过copy向前移动一位
  233. System.arraycopy(elementData, index + 1, elementData, index, j);
  234. }
  235. elementCount--;
  236. //copy会多出来一位,设置位null 让gc做它的工作
  237. elementData[elementCount] = null; /* to let gc do its work */
  238. }
  239. //指定位置插入元素
  240. public synchronized void insertElementAt(E obj, int index) {
  241. modCount++;
  242. if (index > elementCount) {
  243. throw new ArrayIndexOutOfBoundsException(index
  244. + " > " + elementCount);
  245. }
  246. //是否需要扩容
  247. ensureCapacityHelper(elementCount + 1);
  248. //通过arraycopy方法在插入位置向后移动以为,方便元素插入
  249. System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
  250. elementData[index] = obj;
  251. elementCount++;
  252. }
  253. //添加元素
  254. public synchronized void addElement(E obj) {
  255. modCount++;
  256. ensureCapacityHelper(elementCount + 1);
  257. elementData[elementCount++] = obj;
  258. }
  259. //移除元素
  260. public synchronized boolean removeElement(Object obj) {
  261. modCount++;
  262. //通过 indexOf获取在数组中的位置
  263. int i = indexOf(obj);
  264. if (i >= 0) {
  265. removeElementAt(i);
  266. return true;
  267. }
  268. return false;
  269. }
  270. //删除当前数组中的所有元素
  271. public synchronized void removeAllElements() {
  272. modCount++;
  273. //让gc做它的工作
  274. for (int i = 0; i < elementCount; i++)
  275. elementData[i] = null;
  276. elementCount = 0;
  277. }
  278. //克隆函数
  279. public synchronized Object clone() {
  280. try {
  281. @SuppressWarnings("unchecked")
  282. Vector<E> v = (Vector<E>) super.clone();
  283. //将当前Vector的全部元素拷贝到v中
  284. v.elementData = Arrays.copyOf(elementData, elementCount);
  285. v.modCount = 0;
  286. return v;
  287. } catch (CloneNotSupportedException e) {
  288. // this shouldn't happen, since we are Cloneable
  289. throw new InternalError(e);
  290. }
  291. }
  292. //返回存有当前集合所有元素引用的数组
  293. public synchronized Object[] toArray() {
  294. return Arrays.copyOf(elementData, elementCount);
  295. }
  296. // 返回Vector的模板数组。所谓模板数组,即可以将T设为任意的数据类型
  297. @SuppressWarnings("unchecked")
  298. public synchronized <T> T[] toArray(T[] a) {
  299. //如果a的大小小于当前元素的个数 那么就建立新的数组返回
  300. //如果a的大小大于或等于当前元素的大小就将元素copy到a数组中去
  301. if (a.length < elementCount)
  302. return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
  303. System.arraycopy(elementData, 0, a, 0, elementCount);
  304. if (a.length > elementCount)
  305. a[elementCount] = null;
  306. return a;
  307. }
  308. //返回指定位置的元素 这个是内部使用 不加锁,但加锁的那个方法
  309. //也是调用此方法。看下面的get方法就指定了
  310. @SuppressWarnings("unchecked")
  311. E elementData(int index) {
  312. return (E) elementData[index];
  313. }
  314. //加锁了
  315. public synchronized E get(int index) {
  316. if (index >= elementCount)
  317. throw new ArrayIndexOutOfBoundsException(index);
  318. return elementData(index);
  319. }
  320. //修改指定位置的元素
  321. public synchronized E set(int index, E element) {
  322. if (index >= elementCount)
  323. throw new ArrayIndexOutOfBoundsException(index);
  324. E oldValue = elementData(index);
  325. elementData[index] = element;
  326. return oldValue;
  327. }
  328. //添加元素
  329. public synchronized boolean add(E e) {
  330. modCount++;
  331. ensureCapacityHelper(elementCount + 1);
  332. elementData[elementCount++] = e;
  333. return true;
  334. }
  335. //移除匹配元素
  336. public boolean remove(Object o) {
  337. return removeElement(o);
  338. }
  339. //指定位置添加元素
  340. public void add(int index, E element) {
  341. insertElementAt(element, index);
  342. }
  343. //指定位置移除元素 并返回被移除的元素
  344. public synchronized E remove(int index) {
  345. modCount++;
  346. if (index >= elementCount)
  347. throw new ArrayIndexOutOfBoundsException(index);
  348. E oldValue = elementData(index);
  349. int numMoved = elementCount - index - 1;
  350. if (numMoved > 0)
  351. System.arraycopy(elementData, index+1, elementData, index,
  352. numMoved);
  353. elementData[--elementCount] = null; // Let gc do its work
  354. return oldValue;
  355. }
  356. //清空集合当前的所有数据
  357. public void clear() {
  358. removeAllElements();
  359. }
  360. //如果此Vector包含指定Collection中的所有元素,则返回true
  361. public synchronized boolean containsAll(Collection<?> c) {
  362. return super.containsAll(c);
  363. }
  364. //将指定集合的所有数据都添加进当前集合
  365. public synchronized boolean addAll(Collection<? extends E> c) {
  366. modCount++;
  367. Object[] a = c.toArray();
  368. int numNew = a.length;
  369. ensureCapacityHelper(elementCount + numNew);
  370. System.arraycopy(a, 0, elementData, elementCount, numNew);
  371. elementCount += numNew;
  372. return numNew != 0;
  373. }
  374. //当前Vectory中包含指定集合中的元素通通移除掉
  375. public synchronized boolean removeAll(Collection<?> c) {
  376. return super.removeAll(c);
  377. }
  378. //删除“非集合c中的元素”
  379. public synchronized boolean retainAll(Collection<?> c) {
  380. return super.retainAll(c);
  381. }
  382. // 从index位置开始,将集合c中所有元素添加到Vector中
  383. public synchronized boolean addAll(int index, Collection<? extends E> c) {
  384. modCount++;
  385. if (index < 0 || index > elementCount)
  386. throw new ArrayIndexOutOfBoundsException(index);
  387. Object[] a = c.toArray();
  388. int numNew = a.length;
  389. ensureCapacityHelper(elementCount + numNew);
  390. int numMoved = elementCount - index;
  391. if (numMoved > 0)
  392. System.arraycopy(elementData, index, elementData, index + numNew,
  393. numMoved);
  394. System.arraycopy(a, 0, elementData, index, numNew);
  395. elementCount += numNew;
  396. return numNew != 0;
  397. }
  398. //Vector的equals实现,就是调用父类AbstractList的equals方法
  399. public synchronized boolean equals(Object o) {
  400. return super.equals(o);
  401. }
  402. //hashCode码
  403. public synchronized int hashCode() {
  404. return super.hashCode();
  405. }
  406. //将当前对象转换位字符串
  407. public synchronized String toString() {
  408. return super.toString();
  409. }
  410. //获取Vector中fromIndex(包括)到toIndex(不包括)的子集
  411. public synchronized List<E> subList(int fromIndex, int toIndex) {
  412. return Collections.synchronizedList(super.subList(fromIndex, toIndex),
  413. this);
  414. }
  415. //移除Vectory中 fromIndex 到 toIndex位置上的所有元素
  416. protected synchronized void removeRange(int fromIndex, int toIndex) {
  417. modCount++;
  418. int numMoved = elementCount - toIndex;
  419. System.arraycopy(elementData, toIndex, elementData, fromIndex,
  420. numMoved);
  421. // Let gc do its work
  422. int newElementCount = elementCount - (toIndex-fromIndex);
  423. while (elementCount != newElementCount)
  424. elementData[--elementCount] = null;
  425. }
  426. //序列化的写入函数
  427. private void readObject(ObjectInputStream in)
  428. throws IOException, ClassNotFoundException {
  429. ObjectInputStream.GetField gfields = in.readFields();
  430. int count = gfields.get("elementCount", 0);
  431. Object[] data = (Object[])gfields.get("elementData", null);
  432. if (count < 0 || data == null || count > data.length) {
  433. throw new StreamCorruptedException("Inconsistent vector internals");
  434. }
  435. elementCount = count;
  436. elementData = data.clone();
  437. }
  438. //序列的
  439. private void writeObject(java.io.ObjectOutputStream s)
  440. throws java.io.IOException {
  441. final java.io.ObjectOutputStream.PutField fields = s.putFields();
  442. final Object[] data;
  443. synchronized (this) {
  444. fields.put("capacityIncrement", capacityIncrement);
  445. fields.put("elementCount", elementCount);
  446. data = elementData.clone();
  447. }
  448. fields.put("elementData", data);
  449. s.writeFields();
  450. }
  451. ///这是返回ListIterator迭代器的方法,指定迭代的开始位置
  452. public synchronized ListIterator<E> listIterator(int index) {
  453. if (index < 0 || index > elementCount)
  454. throw new IndexOutOfBoundsException("Index: "+index);
  455. return new ListItr(index);
  456. }
  457. //开始位置位 0 定死
  458. public synchronized ListIterator<E> listIterator() {
  459. return new ListItr(0);
  460. }
  461. //这是返回iterator迭代器
  462. public synchronized Iterator<E> iterator() {
  463. return new Itr();
  464. }
  465. /**
  466. * AbstractList.Itr的优化版本 的迭代器实现类
  467. */
  468. private class Itr implements Iterator<E> {
  469. int cursor; //要返回的下一个元素的索引
  470. int lastRet = -1; // 返回最后一个元素的索引; -1如果没有,
  471. int expectedModCount = modCount;
  472. //是否还有下一位
  473. public boolean hasNext() {
  474. return cursor != elementCount;
  475. }
  476. //返回下一位
  477. public E next() {
  478. synchronized (Vector.this) {
  479. checkForComodification();
  480. int i = cursor;
  481. if (i >= elementCount)
  482. throw new NoSuchElementException();
  483. cursor = i + 1;
  484. return elementData(lastRet = i);
  485. }
  486. }
  487. //移除当前所在光标的元素
  488. public void remove() {
  489. if (lastRet == -1)
  490. throw new IllegalStateException();
  491. synchronized (Vector.this) {
  492. checkForComodification();
  493. Vector.this.remove(lastRet);
  494. expectedModCount = modCount;
  495. }
  496. cursor = lastRet;
  497. lastRet = -1;
  498. }
  499. //这是jdk 1.8新增加的方法,重当前迭代位置开始 每个元素都执行 action的指定操作
  500. @Override
  501. public void forEachRemaining(Consumer<? super E> action) {
  502. Objects.requireNonNull(action);
  503. synchronized (Vector.this) {
  504. final int size = elementCount;
  505. int i = cursor;
  506. if (i >= size) {
  507. return;
  508. }
  509. @SuppressWarnings("unchecked")
  510. final E[] elementData = (E[]) Vector.this.elementData;
  511. if (i >= elementData.length) {
  512. throw new ConcurrentModificationException();
  513. }
  514. //循环执行指定操作
  515. while (i != size && modCount == expectedModCount) {
  516. action.accept(elementData[i++]);
  517. }
  518. cursor = i;
  519. lastRet = i - 1;
  520. checkForComodification();
  521. }
  522. }
  523. final void checkForComodification() {
  524. if (modCount != expectedModCount)
  525. throw new ConcurrentModificationException();
  526. }
  527. }
  528. /**
  529. * AbstractList.ListItr的优化版本 ListIterator 实现
  530. */
  531. final class ListItr extends Itr implements ListIterator<E> {
  532. //指定当前迭代的下一个位置的构造
  533. ListItr(int index) {
  534. super();
  535. cursor = index;
  536. }
  537. //是否还有上一位
  538. public boolean hasPrevious() {
  539. return cursor != 0;
  540. }
  541. //下一位在数组中的下标
  542. public int nextIndex() {
  543. return cursor;
  544. }
  545. //上一位在数组中的下标
  546. public int previousIndex() {
  547. return cursor - 1;
  548. }
  549. //返回上以为,并移动光标
  550. public E previous() {
  551. synchronized (Vector.this) {
  552. checkForComodification();
  553. int i = cursor - 1;
  554. if (i < 0)
  555. throw new NoSuchElementException();
  556. cursor = i;
  557. return elementData(lastRet = i);
  558. }
  559. }
  560. //修改当前迭代位置的值
  561. public void set(E e) {
  562. if (lastRet == -1)
  563. throw new IllegalStateException();
  564. synchronized (Vector.this) {
  565. checkForComodification();
  566. Vector.this.set(lastRet, e);
  567. }
  568. }
  569. //在当前迭代位置插入元素
  570. public void add(E e) {
  571. int i = cursor;
  572. synchronized (Vector.this) {
  573. checkForComodification();
  574. Vector.this.add(i, e);
  575. expectedModCount = modCount;
  576. }
  577. cursor = i + 1;
  578. lastRet = -1;
  579. }
  580. }
  581. //遍历执行 action 方法
  582. @Override
  583. public synchronized void forEach(Consumer<? super E> action) {
  584. Objects.requireNonNull(action);
  585. final int expectedModCount = modCount;
  586. @SuppressWarnings("unchecked")
  587. final E[] elementData = (E[]) this.elementData;
  588. final int elementCount = this.elementCount;
  589. for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
  590. action.accept(elementData[i]);
  591. }
  592. if (modCount != expectedModCount) {
  593. throw new ConcurrentModificationException();
  594. }
  595. }
  596. @Override
  597. @SuppressWarnings("unchecked")
  598. public synchronized boolean removeIf(Predicate<? super E> filter) {
  599. Objects.requireNonNull(filter);
  600. // 找出要删除的元素
  601. // 在此阶段从筛选器谓词引发的任何异常
  602. // 将不修改集合
  603. int removeCount = 0;
  604. final int size = elementCount;
  605. final BitSet removeSet = new BitSet(size);
  606. final int expectedModCount = modCount;
  607. for (int i=0; modCount == expectedModCount && i < size; i++) {
  608. @SuppressWarnings("unchecked")
  609. final E element = (E) elementData[i];
  610. if (filter.test(element)) {
  611. removeSet.set(i);
  612. removeCount++;
  613. }
  614. }
  615. if (modCount != expectedModCount) {
  616. throw new ConcurrentModificationException();
  617. }
  618. // 移位幸存元素留在被移除元素留下的空间
  619. final boolean anyToRemove = removeCount > 0;
  620. if (anyToRemove) {
  621. final int newSize = size - removeCount;
  622. for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
  623. i = removeSet.nextClearBit(i);
  624. elementData[j] = elementData[i];
  625. }
  626. for (int k=newSize; k < size; k++) {
  627. elementData[k] = null; // Let gc do its work
  628. }
  629. elementCount = newSize;
  630. if (modCount != expectedModCount) {
  631. throw new ConcurrentModificationException();
  632. }
  633. modCount++;
  634. }
  635. return anyToRemove;
  636. }
  637. @Override
  638. @SuppressWarnings("unchecked")
  639. //循环遍历 将执行operator返回的元素替换当前元素
  640. public synchronized void replaceAll(UnaryOperator<E> operator) {
  641. Objects.requireNonNull(operator);
  642. final int expectedModCount = modCount;
  643. final int size = elementCount;
  644. for (int i=0; modCount == expectedModCount && i < size; i++) {
  645. elementData[i] = operator.apply((E) elementData[i]);
  646. }
  647. if (modCount != expectedModCount) {
  648. throw new ConcurrentModificationException();
  649. }
  650. modCount++;
  651. }
  652. @SuppressWarnings("unchecked")
  653. @Override
  654. //这是给当前的数据进行排序的方法 Comparator 定义了排序的规则
  655. public synchronized void sort(Comparator<? super E> c) {
  656. final int expectedModCount = modCount;
  657. Arrays.sort((E[]) elementData, 0, elementCount, c);
  658. if (modCount != expectedModCount) {
  659. throw new ConcurrentModificationException();
  660. }
  661. modCount++;
  662. }
  663. //当前数据中创建Spliterator
  664. @Override
  665. public Spliterator<E> spliterator() {
  666. return new VectorSpliterator<>(this, null, 0, -1, 0);
  667. }
  668. //与ArrayList Spliterator类似
  669. static final class VectorSpliterator<E> implements Spliterator<E> {
  670. private final Vector<E> list;
  671. private Object[] array;
  672. private int index; // 当前指数,在提前/拆分时修改
  673. private int fence; // -1直到使用;然后是最后一个索引
  674. private int expectedModCount; //栅栏设置时初始化
  675. /** 创建覆盖给定范围的新分裂器*/
  676. VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
  677. int expectedModCount) {
  678. this.list = list;
  679. this.array = array;
  680. this.index = origin;
  681. this.fence = fence;
  682. this.expectedModCount = expectedModCount;
  683. }
  684. private int getFence() { // 首次使用时初始化 返回数组的元素个数
  685. int hi;
  686. if ((hi = fence) < 0) {
  687. synchronized(list) {
  688. array = list.elementData;
  689. expectedModCount = list.modCount;
  690. //hi就等于 = list.elementCount 元素个数
  691. hi = fence = list.elementCount;
  692. }
  693. }
  694. return hi;
  695. }
  696. //重当前对象再分割一个 Spliterator
  697. public Spliterator<E> trySplit() {
  698. // hi = list.elementCount
  699. int hi = getFence(),
  700. lo = index,
  701. //(lo + hi) / 2
  702. mid = (lo + hi) >>> 1;
  703. //看看是否还能拆分出一个 Spliterator 如果拆分不了返回null
  704. return (lo >= mid) ? null :
  705. new VectorSpliterator<E>(list, array, lo, index = mid,
  706. expectedModCount);
  707. }
  708. @SuppressWarnings("unchecked")
  709. //将index + 1位执行 action定义的方法 这是jdk 1.8函数编程所提供出来的
  710. public boolean tryAdvance(Consumer<? super E> action) {
  711. int i;
  712. if (action == null)
  713. throw new NullPointerException();
  714. if (getFence() > (i = index)) {
  715. index = i + 1;
  716. action.accept((E)array[i]);
  717. if (list.modCount != expectedModCount)
  718. throw new ConcurrentModificationException();
  719. return true;
  720. }
  721. return false;
  722. }
  723. @SuppressWarnings("unchecked")
  724. //使用函数式编程 循环数组执行 actioin
  725. public void forEachRemaining(Consumer<? super E> action) {
  726. int i, hi; // 提升从循环访问和检查
  727. Vector<E> lst;
  728. Object[] a;
  729. if (action == null)
  730. throw new NullPointerException();
  731. if ((lst = list) != null) {
  732. if ((hi = fence) < 0) {
  733. synchronized(lst) {
  734. expectedModCount = lst.modCount;
  735. a = array = lst.elementData;
  736. hi = fence = lst.elementCount;
  737. }
  738. }
  739. else
  740. a = array;
  741. if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
  742. //循环执行
  743. while (i < hi)
  744. action.accept((E) a[i++]);
  745. if (lst.modCount == expectedModCount)
  746. return;
  747. }
  748. }
  749. throw new ConcurrentModificationException();
  750. }
  751. //计算当前位置到末尾还有多少个元素
  752. public long estimateSize() {
  753. return (long) (getFence() - index);
  754. }
  755. public int characteristics() {
  756. return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
  757. }
  758. }
  759. }

结论:

  1. Vector是使用数组保存数据,和ArrayList套路一样。
  2. 如果每有指定构造Vector那么它的默认容量位 10 增长系数位 0。
  3. 扩容机制:如果增长系数不位 0 那么就是当前容量 + 增长系数,否则就的当前容量加一倍,具体还是看看上面的ensureCapacity()函数,最大扩容量是Integer.MAX_VALUE。
  4. Vector的克隆函数,即是将全部元素克隆到一个数组中。

    遍历方式

    Iterator迭代器 ```java Iterator iterator = vector.iterator();
     while (iterator.hasNext()){
         iterator.next();
    
    } 或java8的新特性来遍历元素 vector.forEach(a -> {})
**for循环  使用了随机范围的机制**
```java
for (int i = 0; i < vector.size(); i++) {
           vector.get(i);
}

Enumeration遍历

 for (Enumeration enu = vector.elements(); enu.hasMoreElements(); ){
            enu.nextElement();
        }

foreach循环

for (Object o: vector) {
      System.out.println(o);  
}

性能比较

public static void main(String[] args) {
        Vector vec = new Vector();
        for(int i = 0; i < 10000000; i ++)
            vec.add(i);
        iteratorThroughRandomAccess(vec);
        iteratorThroughIterator(vec);
        iteratorThroughJ8(vec);
        iteratorEnumeration(vec);
        iteratorForEach(vec);
    }

public static void iteratorThroughRandomAccess(Vector vector){
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    for (int i = 0; i < vector.size(); i++) {
        vector.get(i);
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("for循环" + interval + "毫秒");
}

public static void iteratorThroughIterator(Vector vector){
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    Iterator iterator = vector.iterator();
    while (iterator.hasNext()){
        iterator.next();
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("迭代器遍历" + interval + "毫秒");
}

public static void iteratorThroughJ8(Vector vector){
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    vector.forEach(a -> {});
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("jdk1.8新特性遍历" + interval + "毫秒");
}

public static void iteratorEnumeration(Vector vector){
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    for (Enumeration enu = vector.elements(); enu.hasMoreElements(); ){
        enu.nextElement();
    }
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("java 枚举遍历历" + interval + "毫秒");
}

public  static void iteratorForEach(Vector vector){
    long startTime;
    long endTime;
    startTime = System.currentTimeMillis();
    for (Object o: vector) ;
    endTime = System.currentTimeMillis();
    long interval = endTime - startTime;
    System.out.println("foreach循环" + interval + "毫秒");

}

执行结果:
使用随机访问遍历479毫秒
迭代器 iterator遍历242毫秒
jdk1.8新特性遍历58毫秒
java 枚举遍历历149毫秒
foreach循环143毫秒