当前位置:   article > 正文

Java集合框架04-Vector详解_java 的vector是什么结构

java 的vector是什么结构

1、Vector介绍

Vector是矢量队列,它继承了AbstractList,实现了List、 RandomAccess, Cloneable, java.io.Serializable接口。

  • Vector继承了AbstractList,实现了List,它是一个队列,因此实现了相应的添加、删除、修改、遍历等功能。
  • Vector实现了RandomAccess接口,因此可以随机访问。
  • Vector实现了Cloneable,重载了clone()方法,因此可以进行克隆。
  • Vector实现了Serializable接口,因此可以进行序列化。
  • Vector的操作是线程安全的。

2、Vector和ArrayList的关系

Vector的数据结构和ArrayList差不多,包含了3个成员变量:elementData,elementCount,capacityIncrement。 
(1)elementData是Object[]的数组,初始大小为10,会不断的增长。 
(2)elementCount是元素的个数。 
(3)capacityIncrement是动态数组增长的系数。

3、继承结构

  1. java.lang.Object
  2. ↳ java.util.AbstractCollection<E>
  3. ↳ java.util.AbstractList<E>
  4. ↳ java.util.Vector<E>
  5. public class Vector<E>
  6. extends AbstractList<E>
  7. implements List<E>, RandomAccess, Cloneable, java.io.Serializable {}

4、源码分析

  1. package list;
  2. import java.util.*;
  3. import java.util.function.Consumer;
  4. import java.util.function.Predicate;
  5. import java.util.function.UnaryOperator;
  6. public class Vector<E>
  7. extends AbstractList<E>
  8. implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
  9. //当前数组
  10. protected Object[] elementData;
  11. //当前数组元素个数
  12. protected int elementCount;
  13. // capacityIncrement,扩增容量:代表当列表元素满了之后增加的容量。
  14. //如果不设置capacityIncrement,那么Vector容量扩展时默认将扩展两倍
  15. protected int capacityIncrement;
  16. //序列化uid
  17. private static final long serialVersionUID = -2767605614048989439L;
  18. /**
  19. * 创建一个带有指定容量和扩增容量的Vector
  20. * @param initialCapacity 初始化容量
  21. * @param capacityIncrement 列表元素满了之后增加的容量
  22. * @throws IllegalArgumentException 如果指定容量为负
  23. */
  24. public Vector(int initialCapacity, int capacityIncrement) {
  25. super();
  26. if (initialCapacity < 0)
  27. throw new IllegalArgumentException("Illegal Capacity: "+
  28. initialCapacity);
  29. this.elementData = new Object[initialCapacity];//创建一个指定容量的数组
  30. this.capacityIncrement = capacityIncrement;
  31. }
  32. /**
  33. * 创建一个带有指定容量和扩增容量为空的Vector
  34. */
  35. public Vector(int initialCapacity) {
  36. this(initialCapacity, 0);
  37. }
  38. /**
  39. * 创建一个带有指定容量和扩增容量为空的Vector
  40. */
  41. public Vector() {
  42. this(10);
  43. }
  44. /**
  45. * 创建一个包含指定集合中元素的Vector,
  46. * - 顺序按照集合的iterator
  47. * - <? extends E> 协变: 当你传入的集合是 E 的子类时,那么就可以协变。
  48. */
  49. public Vector(Collection<? extends E> c) {
  50. elementData = c.toArray();
  51. elementCount = elementData.length;
  52. // c.toArray might (incorrectly) not return Object[] (see 6260652)
  53. if (elementData.getClass() != Object[].class)
  54. elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
  55. }
  56. /**
  57. * 将Vector中的元素拷贝到指定数组中
  58. */
  59. public synchronized void copyInto(Object[] anArray) {
  60. System.arraycopy(elementData, 0, anArray, 0, elementCount);
  61. }
  62. /**
  63. * 将底层数组的容量调整为当前vector实际元素的个数,来释放空间。
  64. */
  65. public synchronized void trimToSize() {
  66. modCount++;
  67. int oldCapacity = elementData.length;
  68. if (elementCount < oldCapacity) {
  69. elementData = Arrays.copyOf(elementData, elementCount);
  70. }
  71. }
  72. /**
  73. * 确保最小容量至少是minCapacity,如果不够,增长Vector的容量
  74. */
  75. public synchronized void ensureCapacity(int minCapacity) {
  76. if (minCapacity > 0) {
  77. modCount++;
  78. ensureCapacityHelper(minCapacity);
  79. }
  80. }
  81. /**
  82. * 这里注释解释,这个方法是异步(也就是能被多个线程同时访问)的,
  83. * 原因是为了让同步方法都能调用到这个检测容量的方法,
  84. */
  85. private void ensureCapacityHelper(int minCapacity) {
  86. // overflow-conscious code
  87. if (minCapacity - elementData.length > 0)
  88. //容量不够,就扩增,核心方法
  89. grow(minCapacity);
  90. }
  91. /**
  92. * 因为某些VM会在数组中保留一些头字,尝试分配这个最大存储容量,可能会导致array容量大于VM的limit,最终导致OutOfMemoryError。
  93. */
  94. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  95. /**
  96. * 容量核心方法,增加容量
  97. */
  98. private void grow(int minCapacity) {
  99. // overflow-conscious code
  100. //原来的数组容量
  101. int oldCapacity = elementData.length;
  102. //如果capacityIncrement>0,就加capacityIncrement,如果不是就增加一倍。
  103. int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
  104. capacityIncrement : oldCapacity);
  105. //如果扩容后的容量还是比指定的最小容量小
  106. if (newCapacity - minCapacity < 0)
  107. newCapacity = minCapacity;//新容量=最小容量
  108. //如果扩容后的容量比最大数组容量还要大
  109. if (newCapacity - MAX_ARRAY_SIZE > 0)
  110. newCapacity = hugeCapacity(minCapacity);//新容量=最大容量
  111. elementData = Arrays.copyOf(elementData, newCapacity);//新数组大小
  112. }
  113. private static int hugeCapacity(int minCapacity) {
  114. if (minCapacity < 0) // overflow
  115. throw new OutOfMemoryError();
  116. return (minCapacity > MAX_ARRAY_SIZE) ?
  117. Integer.MAX_VALUE :
  118. MAX_ARRAY_SIZE;
  119. }
  120. /**
  121. * 设置vector的容量大小,如果新容量大于当前的容量,则增加items到vector的末尾
  122. * 如果新容量小于当前容量,将vector从新容量到末尾处丢弃
  123. */
  124. public synchronized void setSize(int newSize) {
  125. modCount++;
  126. if (newSize > elementCount) {
  127. ensureCapacityHelper(newSize);
  128. } else {
  129. for (int i = newSize ; i < elementCount ; i++) {
  130. elementData[i] = null;
  131. }
  132. }
  133. elementCount = newSize;
  134. }
  135. /**
  136. * 获取vector的容量
  137. */
  138. public synchronized int capacity() {
  139. return elementData.length;
  140. }
  141. /**
  142. * 返回 vector 元素个数
  143. */
  144. public synchronized int size() {
  145. return elementCount;
  146. }
  147. /**
  148. * 判断vector元素是否为空
  149. */
  150. public synchronized boolean isEmpty() {
  151. return elementCount == 0;
  152. }
  153. /**
  154. * 返回一个包含vector所有元素的枚举
  155. * while (elements.hasMoreElements()) {
  156. * String s = elements.nextElement();
  157. * }
  158. */
  159. public Enumeration<E> elements() {
  160. // 通过匿名类实现Enumeration
  161. return new Enumeration<E>() {
  162. int count = 0;
  163. // 是否存在下一个元素
  164. public boolean hasMoreElements() {
  165. return count < elementCount;
  166. }
  167. // 获取下一个元素
  168. public E nextElement() {
  169. synchronized (Vector.this) {
  170. if (count < elementCount) {
  171. return elementData(count++);
  172. }
  173. }
  174. throw new NoSuchElementException("Vector Enumeration");
  175. }
  176. };
  177. }
  178. /**
  179. * 返回这个vector是否包含指定元素
  180. */
  181. public boolean contains(Object o) {
  182. return indexOf(o, 0) >= 0;
  183. }
  184. /**
  185. * 返回这个vector中第一次出现指定元素的下标,如果不包括这个元素返回-1
  186. * 从0开始查找
  187. */
  188. public int indexOf(Object o) {
  189. return indexOf(o, 0);
  190. }
  191. /**
  192. *从指定的位置向后开始查找vector中第一次出现这个元素的下标
  193. * 如果没有返回-1
  194. */
  195. public synchronized int indexOf(Object o, int index) {
  196. if (o == null) {
  197. for (int i = index ; i < elementCount ; i++)
  198. if (elementData[i]==null)
  199. return i;
  200. } else {
  201. for (int i = index ; i < elementCount ; i++)
  202. if (o.equals(elementData[i]))
  203. return i;
  204. }
  205. return -1;
  206. }
  207. /**
  208. * 返回在vector中最后一次出现指定元素的角标
  209. * 如果vector不包含这个元素则返回-1
  210. */
  211. public synchronized int lastIndexOf(Object o) {
  212. return lastIndexOf(o, elementCount-1);
  213. }
  214. /**
  215. * 返回在vector中最后一次出现指定元素的角标
  216. * - 就是从指定位置向前寻找第一次出现的指定元素的角标
  217. * - 如果找不到返回-1
  218. */
  219. public synchronized int lastIndexOf(Object o, int index) {
  220. if (index >= elementCount)
  221. throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
  222. if (o == null) {
  223. for (int i = index; i >= 0; i--)
  224. if (elementData[i]==null)
  225. return i;
  226. } else {
  227. for (int i = index; i >= 0; i--)
  228. if (o.equals(elementData[i]))
  229. return i;
  230. }
  231. return -1;
  232. }
  233. /**
  234. * 返回指定下标的元素
  235. * -- 这个只判断了index>elcmentCount
  236. */
  237. public synchronized E elementAt(int index) {
  238. if (index >= elementCount) {
  239. throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
  240. }
  241. return elementData(index);
  242. }
  243. /**
  244. *返回vector中的第一个元素
  245. * -- 如果没有元素会报错NoSuchElementException
  246. */
  247. public synchronized E firstElement() {
  248. if (elementCount == 0) {
  249. throw new NoSuchElementException();
  250. }
  251. return elementData(0);
  252. }
  253. /**
  254. *返回vector中的最后一个元素,
  255. * -- 如果没有会报错NoSuchElementException
  256. */
  257. public synchronized E lastElement() {
  258. if (elementCount == 0) {
  259. throw new NoSuchElementException();
  260. }
  261. return elementData(elementCount - 1);
  262. }
  263. /**
  264. * 在指定位置设置指定元素,原来位置的元素会被丢弃
  265. */
  266. public synchronized void setElementAt(E obj, int index) {
  267. if (index >= elementCount) {
  268. throw new ArrayIndexOutOfBoundsException(index + " >= " +
  269. elementCount);
  270. }
  271. elementData[index] = obj;
  272. }
  273. /**
  274. * 删除指定位置的元素
  275. * -- 指定位置后面如果还有元素,将后面的元素都向下移动1
  276. * -- 元素长度-1
  277. */
  278. public synchronized void removeElementAt(int index) {
  279. modCount++;
  280. if (index >= elementCount) {
  281. throw new ArrayIndexOutOfBoundsException(index + " >= " +
  282. elementCount);
  283. }
  284. else if (index < 0) {
  285. throw new ArrayIndexOutOfBoundsException(index);
  286. }
  287. int j = elementCount - index - 1;//指定位置后还有多少元素(不含指定元素)
  288. if (j > 0) {//如果指定位置后面还有元素
  289. //将指定位置后面的元素向前移动
  290. System.arraycopy(elementData, index + 1, elementData, index, j);
  291. }
  292. elementCount--;
  293. elementData[elementCount] = null;//将元素顶部置空,方便回收器回收
  294. }
  295. /**
  296. * 在指定位置插入元素
  297. * -- 将指定位置后面的元素(包括指定位置)向上移动一位
  298. */
  299. public synchronized void insertElementAt(E obj, int index) {
  300. modCount++;
  301. if (index > elementCount) {
  302. throw new ArrayIndexOutOfBoundsException(index
  303. + " > " + elementCount);
  304. }
  305. ensureCapacityHelper(elementCount + 1);//确保容量够用
  306. //将指定位置及其后面的元素向上移动一位
  307. System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
  308. //在指定位置插入元素
  309. elementData[index] = obj;
  310. //元素长度+1
  311. elementCount++;
  312. }
  313. /**
  314. * 在vector的元素末尾添加一个元素
  315. */
  316. public synchronized void addElement(E obj) {
  317. modCount++;
  318. ensureCapacityHelper(elementCount + 1);//确保容量够用
  319. elementData[elementCount++] = obj;
  320. }
  321. /**
  322. * 移除在vector中第一次出现的指定元素
  323. * -- 如果vector中真的包含这个元素,这个元素后面的都要向下移动一位
  324. */
  325. public synchronized boolean removeElement(Object obj) {
  326. modCount++;
  327. int i = indexOf(obj);//查找元素在vector中的位置,如果没有返回-1
  328. if (i >= 0) {
  329. //如果有这个元素,删除
  330. removeElementAt(i);
  331. return true;
  332. }
  333. return false;
  334. }
  335. /**
  336. * 移除vector中的所有元素,让它的元素大小为0
  337. */
  338. public synchronized void removeAllElements() {
  339. modCount++;
  340. // 让回收器回收
  341. for (int i = 0; i < elementCount; i++)
  342. elementData[i] = null;
  343. elementCount = 0;
  344. }
  345. /**
  346. * 由于实现了Cloneable,这个是深度克隆
  347. */
  348. public synchronized Object clone() {
  349. try {
  350. @SuppressWarnings("unchecked")
  351. Vector<E> v = (Vector<E>) super.clone();
  352. v.elementData = Arrays.copyOf(elementData, elementCount);
  353. v.modCount = 0;
  354. return v;
  355. } catch (CloneNotSupportedException e) {
  356. // this shouldn't happen, since we are Cloneable
  357. throw new InternalError(e);
  358. }
  359. }
  360. /**
  361. * 返回一个数组,包含vector中的所有元素
  362. */
  363. public synchronized Object[] toArray() {
  364. return Arrays.copyOf(elementData, elementCount);
  365. }
  366. /**
  367. * 返回指定类型的数组
  368. * - 这里T[] 可以是vector中指定的类型的父类
  369. */
  370. @SuppressWarnings("unchecked")
  371. public synchronized <T> T[] toArray(T[] a) {
  372. if (a.length < elementCount)
  373. return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
  374. System.arraycopy(elementData, 0, a, 0, elementCount);
  375. if (a.length > elementCount)
  376. a[elementCount] = null;
  377. return a;
  378. }
  379. // Positional Access Operations
  380. //返回指定位置的元素
  381. //-- 没有检查,这个方法被内部方法调用
  382. @SuppressWarnings("unchecked")
  383. E elementData(int index) {
  384. return (E) elementData[index];
  385. }
  386. /**
  387. * 获取指定位置的元素
  388. */
  389. public synchronized E get(int index) {
  390. if (index >= elementCount)
  391. throw new ArrayIndexOutOfBoundsException(index);
  392. return elementData(index);
  393. }
  394. /**
  395. * 在vector的指定位置代替指定的元素
  396. * -- 返回指定位置原来的元素
  397. */
  398. public synchronized E set(int index, E element) {
  399. if (index >= elementCount)
  400. throw new ArrayIndexOutOfBoundsException(index);
  401. E oldValue = elementData(index);
  402. elementData[index] = element;
  403. return oldValue;
  404. }
  405. /**
  406. * 增加指定的元素到vector
  407. */
  408. public synchronized boolean add(E e) {
  409. modCount++;
  410. ensureCapacityHelper(elementCount + 1);//确保vector的容量够用
  411. elementData[elementCount++] = e;//填充元素
  412. return true;
  413. }
  414. /**
  415. * 移除vector中第一次出现的指定元素
  416. */
  417. public boolean remove(Object o) {
  418. return removeElement(o);
  419. }
  420. /**
  421. * 在指定位置插入指定元素
  422. * --向上移动当前元素和后续元素
  423. */
  424. public void add(int index, E element) {
  425. insertElementAt(element, index);
  426. }
  427. /**
  428. *移除指定位置的元素
  429. * -- 返回指定位的原来元素
  430. * -- 向下移动指定位置后续的元素
  431. */
  432. public synchronized E remove(int index) {
  433. modCount++;
  434. if (index >= elementCount)
  435. throw new ArrayIndexOutOfBoundsException(index);
  436. E oldValue = elementData(index);//获取指定位的元素
  437. int numMoved = elementCount - index - 1;//获取指定位置后面的元素个数
  438. if (numMoved > 0)
  439. //向下移动指定位置的后续元素
  440. System.arraycopy(elementData, index+1, elementData, index,
  441. numMoved);
  442. elementData[--elementCount] = null; // Let gc do its work
  443. return oldValue;
  444. }
  445. /**
  446. * 清除vector中的所有元素
  447. */
  448. public void clear() {
  449. removeAllElements();
  450. }
  451. // Bulk Operations
  452. /**这个方法是调用父类AbstractCollection的方法实现的
  453. * vector是否包含指定集合中的所有元素
  454. * -- 如果指定集合中有一个元素不包含则返回false
  455. */
  456. public synchronized boolean containsAll(Collection<?> c) {
  457. return super.containsAll(c);
  458. }
  459. /**
  460. * 添加指定集合中的所有元素到vector的末尾,
  461. * --按照指定集合iterator返回的顺序
  462. */
  463. public synchronized boolean addAll(Collection<? extends E> c) {
  464. modCount++;
  465. Object[] a = c.toArray();//将集合转化成数组
  466. int numNew = a.length;//集合的长度
  467. ensureCapacityHelper(elementCount + numNew);//确保容量
  468. System.arraycopy(a, 0, elementData, elementCount, numNew);//拷贝
  469. elementCount += numNew;
  470. return numNew != 0;
  471. }
  472. /**
  473. * 这个方法是调用父类AbstractCollection的方法实现的
  474. * 删除vector中指定集合的所有元素
  475. * -- 如 vector[2,5,7,10,3,] c[5,3,15] 指行这个方法后,vector中[2,7,10,3]
  476. */
  477. public synchronized boolean removeAll(Collection<?> c) {
  478. return super.removeAll(c);
  479. }
  480. /**
  481. * 这个是调用父类AbstractCollection方法实现的
  482. * 保留vector中指定集合的所有元素
  483. * -- 如 vector[2,5,7,10,3,] c[5,3,15] 指行这个方法后,vector中[5,3]
  484. */
  485. public synchronized boolean retainAll(Collection<?> c) {
  486. return super.retainAll(c);
  487. }
  488. /**
  489. * 在vector的指定位置添加指定集合中的所有元素
  490. * -- 向右移动指定位置及其后继的元素
  491. */
  492. public synchronized boolean addAll(int index, Collection<? extends E> c) {
  493. modCount++;
  494. if (index < 0 || index > elementCount)
  495. throw new ArrayIndexOutOfBoundsException(index);
  496. Object[] a = c.toArray();
  497. int numNew = a.length;
  498. ensureCapacityHelper(elementCount + numNew);
  499. int numMoved = elementCount - index;//指定位置及其后继元素的个数
  500. if (numMoved > 0)
  501. //向后移动集合元素大小个距离
  502. System.arraycopy(elementData, index, elementData, index + numNew,
  503. numMoved);
  504. //将集合元素添加到vector中
  505. System.arraycopy(a, 0, elementData, index, numNew);
  506. elementCount += numNew;
  507. return numNew != 0;
  508. }
  509. /**
  510. * 这个方法是调用父类AbstractList方法实现的
  511. * 比较vector和指定的对象
  512. * 如果 这个对象是List对象而且集合中元素和vector中的元素一致则返回true,否则返回false
  513. */
  514. public synchronized boolean equals(Object o) {
  515. return super.equals(o);
  516. }
  517. /**
  518. * 返回vector的hashCode
  519. */
  520. public synchronized int hashCode() {
  521. return super.hashCode();
  522. }
  523. /**
  524. * 调用了父类的AbstractCollection中的方法
  525. * 返回了这个vector的表示string,包括每一个元素的表示
  526. */
  527. public synchronized String toString() {
  528. return super.toString();
  529. }
  530. /**
  531. *
  532. *返回list中的[fromIndex,toIndex]的子视图
  533. * -- 如果fromIndex==toIndex则返回的是一个空视图
  534. * -- 这个子视图是这个List的反射
  535. */
  536. public synchronized List<E> subList(int fromIndex, int toIndex) {
  537. return Collections.synchronizedList(super.subList(fromIndex, toIndex));
  538. }
  539. /**
  540. * 移除list中[fromIndex,toIndex)范围的元素
  541. * toIndex及其后继元素向前移动toIndex-fromIndex位
  542. */
  543. protected synchronized void removeRange(int fromIndex, int toIndex) {
  544. modCount++;
  545. int numMoved = elementCount - toIndex;//获取要移动元素的个数
  546. System.arraycopy(elementData, toIndex, elementData, fromIndex,
  547. numMoved);
  548. // 回收
  549. int newElementCount = elementCount - (toIndex-fromIndex);
  550. while (elementCount != newElementCount)
  551. elementData[--elementCount] = null;
  552. }
  553. /**
  554. * 序列化
  555. */
  556. private void writeObject(java.io.ObjectOutputStream s)
  557. throws java.io.IOException {
  558. final java.io.ObjectOutputStream.PutField fields = s.putFields();
  559. final Object[] data;
  560. synchronized (this) {
  561. fields.put("capacityIncrement", capacityIncrement);
  562. fields.put("elementCount", elementCount);
  563. data = elementData.clone();
  564. }
  565. fields.put("elementData", data);
  566. s.writeFields();
  567. }
  568. //--------下面的视图iterator,可以参考ArrayList的
  569. /**
  570. * 迭代器
  571. */
  572. public synchronized ListIterator<E> listIterator(int index) {
  573. if (index < 0 || index > elementCount)
  574. throw new IndexOutOfBoundsException("Index: "+index);
  575. return new ListItr(index);
  576. }
  577. /**
  578. * Returns a list iterator over the elements in this list (in proper
  579. * sequence)
  580. */
  581. public synchronized ListIterator<E> listIterator() {
  582. return new ListItr(0);
  583. }
  584. /**
  585. * Returns an iterator over the elements in this list in proper sequence.
  586. *
  587. * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
  588. *
  589. * @return an iterator over the elements in this list in proper sequence
  590. */
  591. public synchronized Iterator<E> iterator() {
  592. return new Itr();
  593. }
  594. /**
  595. * An optimized version of AbstractList.Itr
  596. */
  597. private class Itr implements Iterator<E> {
  598. int cursor; // index of next element to return
  599. int lastRet = -1; // index of last element returned; -1 if no such
  600. int expectedModCount = modCount;
  601. public boolean hasNext() {
  602. // Racy but within spec, since modifications are checked
  603. // within or after synchronization in next/previous
  604. return cursor != elementCount;
  605. }
  606. public E next() {
  607. synchronized (Vector.this) {
  608. checkForComodification();
  609. int i = cursor;
  610. if (i >= elementCount)
  611. throw new NoSuchElementException();
  612. cursor = i + 1;
  613. return elementData(lastRet = i);
  614. }
  615. }
  616. public void remove() {
  617. if (lastRet == -1)
  618. throw new IllegalStateException();
  619. synchronized (Vector.this) {
  620. checkForComodification();
  621. Vector.this.remove(lastRet);
  622. expectedModCount = modCount;
  623. }
  624. cursor = lastRet;
  625. lastRet = -1;
  626. }
  627. @Override
  628. public void forEachRemaining(Consumer<? super E> action) {
  629. Objects.requireNonNull(action);
  630. synchronized (Vector.this) {
  631. final int size = elementCount;
  632. int i = cursor;
  633. if (i >= size) {
  634. return;
  635. }
  636. @SuppressWarnings("unchecked")
  637. final E[] elementData = (E[]) Vector.this.elementData;
  638. if (i >= elementData.length) {
  639. throw new ConcurrentModificationException();
  640. }
  641. while (i != size && modCount == expectedModCount) {
  642. action.accept(elementData[i++]);
  643. }
  644. // update once at end of iteration to reduce heap write traffic
  645. cursor = i;
  646. lastRet = i - 1;
  647. checkForComodification();
  648. }
  649. }
  650. final void checkForComodification() {
  651. if (modCount != expectedModCount)
  652. throw new ConcurrentModificationException();
  653. }
  654. }
  655. /**
  656. * An optimized version of AbstractList.ListItr
  657. */
  658. final class ListItr extends Itr implements ListIterator<E> {
  659. ListItr(int index) {
  660. super();
  661. cursor = index;
  662. }
  663. public boolean hasPrevious() {
  664. return cursor != 0;
  665. }
  666. public int nextIndex() {
  667. return cursor;
  668. }
  669. public int previousIndex() {
  670. return cursor - 1;
  671. }
  672. public E previous() {
  673. synchronized (Vector.this) {
  674. checkForComodification();
  675. int i = cursor - 1;
  676. if (i < 0)
  677. throw new NoSuchElementException();
  678. cursor = i;
  679. return elementData(lastRet = i);
  680. }
  681. }
  682. public void set(E e) {
  683. if (lastRet == -1)
  684. throw new IllegalStateException();
  685. synchronized (Vector.this) {
  686. checkForComodification();
  687. Vector.this.set(lastRet, e);
  688. }
  689. }
  690. public void add(E e) {
  691. int i = cursor;
  692. synchronized (Vector.this) {
  693. checkForComodification();
  694. Vector.this.add(i, e);
  695. expectedModCount = modCount;
  696. }
  697. cursor = i + 1;
  698. lastRet = -1;
  699. }
  700. }
  701. @Override
  702. public synchronized void forEach(Consumer<? super E> action) {
  703. Objects.requireNonNull(action);
  704. final int expectedModCount = modCount;
  705. @SuppressWarnings("unchecked")
  706. final E[] elementData = (E[]) this.elementData;
  707. final int elementCount = this.elementCount;
  708. for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
  709. action.accept(elementData[i]);
  710. }
  711. if (modCount != expectedModCount) {
  712. throw new ConcurrentModificationException();
  713. }
  714. }
  715. @Override
  716. @SuppressWarnings("unchecked")
  717. public synchronized boolean removeIf(Predicate<? super E> filter) {
  718. Objects.requireNonNull(filter);
  719. // figure out which elements are to be removed
  720. // any exception thrown from the filter predicate at this stage
  721. // will leave the collection unmodified
  722. int removeCount = 0;
  723. final int size = elementCount;
  724. final BitSet removeSet = new BitSet(size);
  725. final int expectedModCount = modCount;
  726. for (int i=0; modCount == expectedModCount && i < size; i++) {
  727. @SuppressWarnings("unchecked")
  728. final E element = (E) elementData[i];
  729. if (filter.test(element)) {
  730. removeSet.set(i);
  731. removeCount++;
  732. }
  733. }
  734. if (modCount != expectedModCount) {
  735. throw new ConcurrentModificationException();
  736. }
  737. // shift surviving elements left over the spaces left by removed elements
  738. final boolean anyToRemove = removeCount > 0;
  739. if (anyToRemove) {
  740. final int newSize = size - removeCount;
  741. for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
  742. i = removeSet.nextClearBit(i);
  743. elementData[j] = elementData[i];
  744. }
  745. for (int k=newSize; k < size; k++) {
  746. elementData[k] = null; // Let gc do its work
  747. }
  748. elementCount = newSize;
  749. if (modCount != expectedModCount) {
  750. throw new ConcurrentModificationException();
  751. }
  752. modCount++;
  753. }
  754. return anyToRemove;
  755. }
  756. @Override
  757. @SuppressWarnings("unchecked")
  758. public synchronized void replaceAll(UnaryOperator<E> operator) {
  759. Objects.requireNonNull(operator);
  760. final int expectedModCount = modCount;
  761. final int size = elementCount;
  762. for (int i=0; modCount == expectedModCount && i < size; i++) {
  763. elementData[i] = operator.apply((E) elementData[i]);
  764. }
  765. if (modCount != expectedModCount) {
  766. throw new ConcurrentModificationException();
  767. }
  768. modCount++;
  769. }
  770. @SuppressWarnings("unchecked")
  771. @Override
  772. public synchronized void sort(Comparator<? super E> c) {
  773. final int expectedModCount = modCount;
  774. Arrays.sort((E[]) elementData, 0, elementCount, c);
  775. if (modCount != expectedModCount) {
  776. throw new ConcurrentModificationException();
  777. }
  778. modCount++;
  779. }
  780. /**
  781. * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
  782. * and <em>fail-fast</em> {@link Spliterator} over the elements in this
  783. * list.
  784. *
  785. * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
  786. * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
  787. * Overriding implementations should document the reporting of additional
  788. * characteristic values.
  789. *
  790. * @return a {@code Spliterator} over the elements in this list
  791. * @since 1.8
  792. */
  793. @Override
  794. public Spliterator<E> spliterator() {
  795. return new VectorSpliterator<>(this, null, 0, -1, 0);
  796. }
  797. /** Similar to ArrayList Spliterator */
  798. static final class VectorSpliterator<E> implements Spliterator<E> {
  799. private final Vector<E> list;
  800. private Object[] array;
  801. private int index; // current index, modified on advance/split
  802. private int fence; // -1 until used; then one past last index
  803. private int expectedModCount; // initialized when fence set
  804. /** Create new spliterator covering the given range */
  805. VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
  806. int expectedModCount) {
  807. this.list = list;
  808. this.array = array;
  809. this.index = origin;
  810. this.fence = fence;
  811. this.expectedModCount = expectedModCount;
  812. }
  813. private int getFence() { // initialize on first use
  814. int hi;
  815. if ((hi = fence) < 0) {
  816. synchronized(list) {
  817. array = list.elementData;
  818. expectedModCount = list.modCount;
  819. hi = fence = list.elementCount;
  820. }
  821. }
  822. return hi;
  823. }
  824. public Spliterator<E> trySplit() {
  825. int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
  826. return (lo >= mid) ? null :
  827. new VectorSpliterator<E>(list, array, lo, index = mid,
  828. expectedModCount);
  829. }
  830. @SuppressWarnings("unchecked")
  831. public boolean tryAdvance(Consumer<? super E> action) {
  832. int i;
  833. if (action == null)
  834. throw new NullPointerException();
  835. if (getFence() > (i = index)) {
  836. index = i + 1;
  837. action.accept((E)array[i]);
  838. if (list.modCount != expectedModCount)
  839. throw new ConcurrentModificationException();
  840. return true;
  841. }
  842. return false;
  843. }
  844. @SuppressWarnings("unchecked")
  845. public void forEachRemaining(Consumer<? super E> action) {
  846. int i, hi; // hoist accesses and checks from loop
  847. Vector<E> lst; Object[] a;
  848. if (action == null)
  849. throw new NullPointerException();
  850. if ((lst = list) != null) {
  851. if ((hi = fence) < 0) {
  852. synchronized(lst) {
  853. expectedModCount = lst.modCount;
  854. a = array = lst.elementData;
  855. hi = fence = lst.elementCount;
  856. }
  857. }
  858. else
  859. a = array;
  860. if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
  861. while (i < hi)
  862. action.accept((E) a[i++]);
  863. if (lst.modCount == expectedModCount)
  864. return;
  865. }
  866. }
  867. throw new ConcurrentModificationException();
  868. }
  869. public long estimateSize() {
  870. return (long) (getFence() - index);
  871. }
  872. public int characteristics() {
  873. return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
  874. }
  875. }
  876. }

5、总结

  • Vector底层是数组。
  • 有序。Vector底层是数组,数组是有序的。
  • 可重复。数组是可重复的。
  • 随机访问效率高,增删效率低。通过索引可以很快的查找到对应元素,而增删元素许多元素的位置都要改变。
  • 线程安全。很多方法都是synchronized的。

 

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/243857
推荐阅读
相关标签
  

闽ICP备14008679号