Vector<E>简介

  Vector也是基于数组实现的,是一个动态数组,其容量能自动增长。

  Vector是JDK1.0引入了,它的很多实现方法都加入了同步语句,因此是线程安全的(其实也只是相对安全,有些时候还是要加入同步语句来保证线程的安全),可以用于多线程环境。

  Vector没有丝线Serializable接口,因此它不支持序列化,实现了Cloneable接口,能被克隆,实现了RandomAccess接口,支持快速随机访问。

Vector<E>源码

  如下(已加入详细注释):

  1. /*
  2. * @(#)Vector.java 1.106 06/06/16
  3. *
  4. * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7.  
  8. package java.util;
  9.  
  10. /**
  11. * @author Lee Boynton
  12. * @author Jonathan Payne
  13. * @version 1.106, 06/16/06
  14. * @see Collection
  15. * @see List
  16. * @see ArrayList
  17. * @see LinkedList
  18. * @since JDK1.0
  19. */
  20. public class Vector<E>
  21. extends AbstractList<E>
  22. implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  23. {
  24. // 保存数据数组
  25. protected Object[] elementData;
  26.  
  27. // 实际数据的数量
  28. protected int elementCount;
  29.  
  30. // 容量增长系数
  31. protected int capacityIncrement;
  32.  
  33. // Vector的序列版本号
  34. private static final long serialVersionUID = -2767605614048989439L;
  35.  
  36. // 指定Vector"容量大小"和"增长系数"的构造函数
  37. public Vector(int initialCapacity, int capacityIncrement) {
  38. super();
  39. if (initialCapacity < 0)
  40. throw new IllegalArgumentException("Illegal Capacity: "+
  41. initialCapacity);
  42. this.elementData = new Object[initialCapacity];
  43. this.capacityIncrement = capacityIncrement;
  44. }
  45.  
  46. // 指定Vector容量大小的构造函数
  47. public Vector(int initialCapacity) {
  48. this(initialCapacity, 0);
  49. }
  50.  
  51. // Vector构造函数。默认容量是10。
  52. public Vector() {
  53. this(10);
  54. }
  55.  
  56. // 指定集合的Vector构造函数。
  57. public Vector(Collection<? extends E> c) {
  58. elementData = c.toArray();
  59. elementCount = elementData.length;
  60. // c.toArray might (incorrectly) not return Object[] (see 6260652)
  61. if (elementData.getClass() != Object[].class)
  62. elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
  63. }
  64.  
  65. // 将数组Vector的全部元素都拷贝到数组anArray中
  66. public synchronized void copyInto(Object[] anArray) {
  67. System.arraycopy(elementData, 0, anArray, 0, elementCount);
  68. }
  69.  
  70. // 将当前容量值设为 = 实际元素个数
  71. public synchronized void trimToSize() {
  72. modCount++;
  73. int oldCapacity = elementData.length;
  74. if (elementCount < oldCapacity) {
  75. elementData = Arrays.copyOf(elementData, elementCount);
  76. }
  77. }
  78.  
  79. // 确定Vector的容量。
  80. public synchronized void ensureCapacity(int minCapacity) {
  81. modCount++;
  82. ensureCapacityHelper(minCapacity);
  83. }
  84.  
  85. // 确认“Vector容量”的帮助函数
  86. private void ensureCapacityHelper(int minCapacity) {
  87. int oldCapacity = elementData.length;
  88. // 当Vector的容量不足以容纳当前的全部元素,增加容量大小。
  89. // 若容量增量系数>0(即capacityIncrement>0),则将容量增大当capacityIncrement
  90. // 否则,将容量增大一倍。
  91. if (minCapacity > oldCapacity) {
  92. Object[] oldData = elementData;
  93. int newCapacity = (capacityIncrement > 0) ?
  94. (oldCapacity + capacityIncrement) : (oldCapacity * 2);
  95. if (newCapacity < minCapacity) {
  96. newCapacity = minCapacity;
  97. }
  98. elementData = Arrays.copyOf(elementData, newCapacity);
  99. }
  100. }
  101.  
  102. // 设置容量值为 newSize
  103. public synchronized void setSize(int newSize) {
  104. modCount++;
  105. if (newSize > elementCount) {
  106. // 若"newSize 大于 Vector容量",则调整Vector的大小。
  107. ensureCapacityHelper(newSize);
  108. } else {
  109. // 若"newSize小于/等于 Vector容量",则将newSize位置开始的元素都设置为null
  110. for (int i = newSize ; i < elementCount ; i++) {
  111. elementData[i] = null;
  112. }
  113. }
  114. elementCount = newSize;
  115. }
  116.  
  117. // 返回“Vector的总的容量”
  118. public synchronized int capacity() {
  119. return elementData.length;
  120. }
  121.  
  122. // 返回“Vector的实际大小”,即Vector中元素个数
  123. public synchronized int size() {
  124. return elementCount;
  125. }
  126.  
  127. // 判断Vector是否为空
  128. public synchronized boolean isEmpty() {
  129. return elementCount == 0;
  130. }
  131.  
  132. // 返回“Vector中全部元素对应的Enumeration”
  133. public Enumeration<E> elements() {
  134. // 通过匿名类实现Enumeration
  135. return new Enumeration<E>() {
  136. int count = 0;
  137.  
  138. // 是否存在下一个元素
  139. public boolean hasMoreElements() {
  140. return count < elementCount;
  141. }
  142.  
  143. // 获取下一个元素
  144. public E nextElement() {
  145. synchronized (Vector.this) {
  146. if (count < elementCount) {
  147. return (E)elementData[count++];
  148. }
  149. }
  150. throw new NoSuchElementException("Vector Enumeration");
  151. }
  152. };
  153. }
  154.  
  155. // 返回Vector中是否包含对象(o)
  156. public boolean contains(Object o) {
  157. return indexOf(o, 0) >= 0;
  158. }
  159.  
  160. // 查找并返回元素(o)在Vector中的索引值
  161. public int indexOf(Object o) {
  162. return indexOf(o, 0);
  163. }
  164.  
  165. // 从index位置开始向后查找元素(o)。
  166. // 若找到,则返回元素的索引值;否则,返回-1
  167. public synchronized int indexOf(Object o, int index) {
  168. if (o == null) {
  169. for (int i = index ; i < elementCount ; i++)
  170. if (elementData[i]==null)
  171. return i;
  172. } else {
  173. for (int i = index ; i < elementCount ; i++)
  174. if (o.equals(elementData[i]))
  175. return i;
  176. }
  177. return -1;
  178. }
  179.  
  180. // 从后向前查找元素(o)。并返回元素的索引
  181. public synchronized int lastIndexOf(Object o) {
  182. return lastIndexOf(o, elementCount-1);
  183. }
  184.  
  185. // 从后向前查找元素(o)。开始位置是从前向后的第index个数;
  186. // 若找到,则返回元素的“索引值”;否则,返回-1。
  187. public synchronized int lastIndexOf(Object o, int index) {
  188. if (index >= elementCount)
  189. throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
  190.  
  191. if (o == null) {
  192. // 若查找元素为null,则反向找出null元素,并返回它对应的序号
  193. for (int i = index; i >= 0; i--)
  194. if (elementData[i]==null)
  195. return i;
  196. } else {
  197. // 若查找元素不为null,则反向找出该元素,并返回它对应的序号
  198. for (int i = index; i >= 0; i--)
  199. if (o.equals(elementData[i]))
  200. return i;
  201. }
  202. return -1;
  203. }
  204.  
  205. // 返回Vector中index位置的元素。
  206. // 若index超越数组大小,则抛出异常
  207. public synchronized E elementAt(int index) {
  208. if (index >= elementCount) {
  209. throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
  210. }
  211.  
  212. return (E)elementData[index];
  213. }
  214.  
  215. // 获取Vector中的第一个元素。
  216. // 若失败,则抛出异常!
  217. public synchronized E firstElement() {
  218. if (elementCount == 0) {
  219. throw new NoSuchElementException();
  220. }
  221. return (E)elementData[0];
  222. }
  223.  
  224. // 获取Vector中的最后一个元素。
  225. // 若失败,则抛出异常!
  226. public synchronized E lastElement() {
  227. if (elementCount == 0) {
  228. throw new NoSuchElementException();
  229. }
  230. return (E)elementData[elementCount - 1];
  231. }
  232.  
  233. // 设置index位置的元素值为obj
  234. public synchronized void setElementAt(E obj, int index) {
  235. if (index >= elementCount) {
  236. throw new ArrayIndexOutOfBoundsException(index + " >= " +
  237. elementCount);
  238. }
  239. elementData[index] = obj;
  240. }
  241.  
  242. // 删除index位置的元素
  243. public synchronized void removeElementAt(int index) {
  244. modCount++;
  245. if (index >= elementCount) {
  246. throw new ArrayIndexOutOfBoundsException(index + " >= " +
  247. elementCount);
  248. }
  249. else if (index < 0) {
  250. throw new ArrayIndexOutOfBoundsException(index);
  251. }
  252. int j = elementCount - index - 1;
  253. if (j > 0) {
  254. System.arraycopy(elementData, index + 1, elementData, index, j);
  255. }
  256. elementCount--;
  257. elementData[elementCount] = null;// 通知gc回收
  258. }
  259.  
  260. // 在index位置处插入元素(obj)
  261. public synchronized void insertElementAt(E obj, int index) {
  262. modCount++;
  263. if (index > elementCount) {
  264. throw new ArrayIndexOutOfBoundsException(index
  265. + " > " + elementCount);
  266. }
  267. ensureCapacityHelper(elementCount + 1);
  268. System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
  269. elementData[index] = obj;
  270. elementCount++;
  271. }
  272.  
  273. // 将“元素obj”添加到Vector末尾
  274. public synchronized void addElement(E obj) {
  275. modCount++;
  276. ensureCapacityHelper(elementCount + 1);
  277. elementData[elementCount++] = obj;
  278. }
  279.  
  280. // 在Vector中查找并删除元素obj。
  281. // 成功的话,返回true;否则,返回false。
  282. public synchronized boolean removeElement(Object obj) {
  283. modCount++;
  284. int i = indexOf(obj);
  285. if (i >= 0) {
  286. removeElementAt(i);
  287. return true;
  288. }
  289. return false;
  290. }
  291.  
  292. // 删除Vector中的全部元素
  293. public synchronized void removeAllElements() {
  294. modCount++;
  295. // 将Vector中的全部元素设为null,通知gc回收
  296. for (int i = 0; i < elementCount; i++)
  297. elementData[i] = null;
  298.  
  299. elementCount = 0;
  300. }
  301.  
  302. // 克隆函数
  303. public synchronized Object clone() {
  304. try {
  305. Vector<E> v = (Vector<E>) super.clone();
  306. v.elementData = Arrays.copyOf(elementData, elementCount);
  307. v.modCount = 0;
  308. return v;
  309. } catch (CloneNotSupportedException e) {
  310. // this shouldn't happen, since we are Cloneable
  311. throw new InternalError();
  312. }
  313. }
  314.  
  315. // 返回Object数组
  316. public synchronized Object[] toArray() {
  317. return Arrays.copyOf(elementData, elementCount);
  318. }
  319.  
  320. // 返回Vector的模板数组。所谓模板数组,即可以将T设为任意的数据类型
  321. public synchronized <T> T[] toArray(T[] a) {
  322. // 若数组a的大小 < Vector的元素个数,则新建一个T[]数组,数组大小是“Vector的元素个数”,并将“Vector”全部拷贝到新数组中
  323. if (a.length < elementCount)
  324. return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
  325. // 若数组a的大小 >= Vector的元素个数;则将Vector的全部元素都拷贝到数组a中。
  326. System.arraycopy(elementData, 0, a, 0, elementCount);
  327.  
  328. if (a.length > elementCount)
  329. a[elementCount] = null;
  330.  
  331. return a;
  332. }
  333.  
  334. // Positional Access Operations
  335.  
  336. // 获取index位置的元素
  337. public synchronized E get(int index) {
  338. if (index >= elementCount)
  339. throw new ArrayIndexOutOfBoundsException(index);
  340.  
  341. return (E)elementData[index];
  342. }
  343.  
  344. // 设置index位置的值为element。并返回index位置的原始值
  345. public synchronized E set(int index, E element) {
  346. if (index >= elementCount)
  347. throw new ArrayIndexOutOfBoundsException(index);
  348.  
  349. Object oldValue = elementData[index];
  350. elementData[index] = element;
  351. return (E)oldValue;
  352. }
  353.  
  354. // 将“元素e”添加到Vector最后。
  355. public synchronized boolean add(E e) {
  356. modCount++;
  357. ensureCapacityHelper(elementCount + 1);
  358. elementData[elementCount++] = e;
  359. return true;
  360. }
  361.  
  362. // 删除Vector中的元素o
  363. public boolean remove(Object o) {
  364. return removeElement(o);
  365. }
  366.  
  367. // 在index位置添加元素element
  368. public void add(int index, E element) {
  369. insertElementAt(element, index);
  370. }
  371.  
  372. // 删除index位置的元素,并返回index位置的原始值
  373. public synchronized E remove(int index) {
  374. modCount++;
  375. if (index >= elementCount)
  376. throw new ArrayIndexOutOfBoundsException(index);
  377. Object oldValue = elementData[index];
  378.  
  379. int numMoved = elementCount - index - 1;
  380. if (numMoved > 0)
  381. System.arraycopy(elementData, index+1, elementData, index,
  382. numMoved);
  383. elementData[--elementCount] = null; // Let gc do its work
  384.  
  385. return (E)oldValue;
  386. }
  387.  
  388. // 清空Vector
  389. public void clear() {
  390. removeAllElements();
  391. }
  392.  
  393. // Bulk Operations
  394.  
  395. // 返回Vector是否包含集合c
  396. public synchronized boolean containsAll(Collection<?> c) {
  397. return super.containsAll(c);
  398. }
  399.  
  400. // 将集合c添加到Vector中
  401. public synchronized boolean addAll(Collection<? extends E> c) {
  402. modCount++;
  403. Object[] a = c.toArray();
  404. int numNew = a.length;
  405. ensureCapacityHelper(elementCount + numNew);
  406. // 将集合c的全部元素拷贝到数组elementData中
  407. System.arraycopy(a, 0, elementData, elementCount, numNew);
  408. elementCount += numNew;
  409. return numNew != 0;
  410. }
  411.  
  412. // 删除集合c的全部元素
  413. public synchronized boolean removeAll(Collection<?> c) {
  414. return super.removeAll(c);
  415. }
  416.  
  417. // 删除“非集合c中的元素”
  418. public synchronized boolean retainAll(Collection<?> c) {
  419. return super.retainAll(c);
  420. }
  421.  
  422. // 从index位置开始,将集合c添加到Vector中
  423. public synchronized boolean addAll(int index, Collection<? extends E> c) {
  424. modCount++;
  425. if (index < 0 || index > elementCount)
  426. throw new ArrayIndexOutOfBoundsException(index);
  427.  
  428. Object[] a = c.toArray();
  429. int numNew = a.length;
  430. ensureCapacityHelper(elementCount + numNew);
  431.  
  432. int numMoved = elementCount - index;
  433. if (numMoved > 0)
  434. System.arraycopy(elementData, index, elementData, index + numNew,
  435. numMoved);
  436.  
  437. System.arraycopy(a, 0, elementData, index, numNew);
  438. elementCount += numNew;
  439. return numNew != 0;
  440. }
  441.  
  442. // 返回两个对象是否相等
  443. public synchronized boolean equals(Object o) {
  444. return super.equals(o);
  445. }
  446.  
  447. // 计算哈希值
  448. public synchronized int hashCode() {
  449. return super.hashCode();
  450. }
  451.  
  452. // 调用父类的toString()
  453. public synchronized String toString() {
  454. return super.toString();
  455. }
  456.  
  457. // 获取Vector中fromIndex(包括)到toIndex(不包括)的子集
  458. public synchronized List<E> subList(int fromIndex, int toIndex) {
  459. return Collections.synchronizedList(super.subList(fromIndex, toIndex),
  460. this);
  461. }
  462.  
  463. // 删除Vector中fromIndex到toIndex的元素
  464. protected synchronized void removeRange(int fromIndex, int toIndex) {
  465. modCount++;
  466. int numMoved = elementCount - toIndex;
  467. System.arraycopy(elementData, toIndex, elementData, fromIndex,
  468. numMoved);
  469.  
  470. // Let gc do its work
  471. int newElementCount = elementCount - (toIndex-fromIndex);
  472. while (elementCount != newElementCount)
  473. elementData[--elementCount] = null;
  474. }
  475.  
  476. // java.io.Serializable的写入函数
  477. private synchronized void writeObject(java.io.ObjectOutputStream s)
  478. throws java.io.IOException
  479. {
  480. s.defaultWriteObject();
  481. }
  482. }

简单总结

  Vector的源码实现总体与ArrayList类似,我这里不再做出详细分析,有兴趣的可以对照我前面ArrayList的文章看一下,关于Vector的源码,给出如下几点总结:

  1.Vector有四个不同的构造方法。无参构造方法的容量为默认值10,仅包含容量的构造方法则将容量增长量(从源码中可以看出容量增长量的作用,第二点也会对容量增长量详细说)明置为0。

  2.注意扩充容量的方法ensureCapacityHelper。与ArrayList相同,Vector在每次增加元素(可能是1个,也可能是一组)时,都要调用该方法来确保足够的容量。当容量不足以容纳当前的元素个数时,就先看构造方法中传入的容量增长量参数CapacityIncrement是否为0,如果不为0,就设置新的容量为就容量加上容量增长量,如果为0,就设置新的容量为旧的容量的2倍,如果设置后的新容量还不够,则直接新容量设置为传入的参数(也就是所需的容量),而后同样用Arrays.copyof()方法将元素拷贝到新的数组。

  3.很多方法都加入了synchronized同步语句,来保证线程安全。

  4.同样在查找给定元素索引值等的方法中,源码都将该元素的值分为null和不为null两种情况处理,Vector中也允许元素为null。

  5.其他很多地方都与ArrayList实现大同小异,Vector现在已经基本不再使用。

——————————————————————————————————————————————————————————————

参考资料

【Java集合源码剖析】Vector源码剖析

Java集合源码分析(四)Vector<E>的更多相关文章

  1. java集合源码分析(三):ArrayList

    概述 在前文:java集合源码分析(二):List与AbstractList 和 java集合源码分析(一):Collection 与 AbstractCollection 中,我们大致了解了从 Co ...

  2. java集合源码分析(六):HashMap

    概述 HashMap 是 Map 接口下一个线程不安全的,基于哈希表的实现类.由于他解决哈希冲突的方式是分离链表法,也就是拉链法,因此他的数据结构是数组+链表,在 JDK8 以后,当哈希冲突严重时,H ...

  3. Java 集合源码分析(一)HashMap

    目录 Java 集合源码分析(一)HashMap 1. 概要 2. JDK 7 的 HashMap 3. JDK 1.8 的 HashMap 4. Hashtable 5. JDK 1.7 的 Con ...

  4. Java集合源码分析(三)LinkedList

    LinkedList简介 LinkedList是基于双向循环链表(从源码中可以很容易看出)实现的,除了可以当做链表来操作外,它还可以当做栈.队列和双端队列来使用. LinkedList同样是非线程安全 ...

  5. Java集合源码分析(二)ArrayList

    ArrayList简介 ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长,类似于C语言中的动态申请内存,动态增长内存. ArrayList不是线程安全的,只能用在单线程环境下,多线 ...

  6. java集合源码分析几篇文章

    java集合源码解析https://blog.csdn.net/ns_code/article/category/2362915

  7. Java集合源码分析(四)——Vector

    简介 Vector 是矢量队列,它是JDK1.0版本添加的类.继承于AbstractList,实现了List, RandomAccess, Cloneable这些接口. 和ArrayList不同,Ve ...

  8. Java集合源码分析(四)HashMap

    一.HashMap简介 1.1.HashMap概述 HashMap是基于哈希表的Map接口实现的,它存储的是内容是键值对<key,value>映射.此类不保证映射的顺序,假定哈希函数将元素 ...

  9. Java集合源码分析(一)ArrayList

    前言 在前面的学习集合中只是介绍了集合的相关用法,我们想要更深入的去了解集合那就要通过我们去分析它的源码来了解它.希望对集合有一个更进一步的理解! 既然是看源码那我们要怎么看一个类的源码呢?这里我推荐 ...

随机推荐

  1. WPF入门教程系列八——布局之Grid与UniformGrid(三)

    五. Grid Grid顾名思义就是“网格”,它的子控件被放在一个一个实现定义好的小格子里面,整齐配列. Grid和其他各个Panel比较起来,功能最多也最为复杂.要使用Grid,首先要向RowDef ...

  2. 每天一个linux命令(17):whereis 命令

    whereis命令只能用于程序名的搜索,而且只搜索二进制文件(参数-b).man说明文件(参数-m)和源代码文件(参数-s).如果省略参数,则返回所有信息. 和find相比,whereis查找的速度非 ...

  3. TSQL HASHBYTES 用法

    HashBytes 使用Hash 算法,能够产生高质量的Hash值,大幅度提高识别数据相异的准确性,但是HashBytes函数无法提供100%的准确度,如果业务逻辑要求不允许有误差,那么不要使用任何H ...

  4. Javascript函数中的高级运用

    先介绍一下js中的高阶函数,所谓的高阶函数就是,一个函数中的参数是一个函数或者返回的是一个函数,就称为高阶函数. js中已经提高了一下高阶函数,使用起来非常棒,当然我们也可以自己实现,我介绍几种ES5 ...

  5. 【WP 8.1开发】同时更新多种磁贴

    一般应用程序都会包含多个尺寸的磁贴,如小磁贴(71×71).中磁贴(150×150)和宽磁贴(310×150).常规的磁贴更新做法是用XML文档来定义更新内容,然后再提交更新.如: <tile& ...

  6. Android开发实践:编译VLC-for-android

    最近在Android做流媒体相关的开发,一直想学习一下强大的VLC,正好趁此机会研究研究VLC-for-android的代码,看看优秀的开源音视频播放器是如何实现的.本文总结下在Linux平台下如何编 ...

  7. 深入理解PHP内核(八)变量及数据类型-预定义变量

    原文链接:http://www.orlion.ga/249/ PHP脚本在执行的时候用户全局变量(在用户空间显示定义的变量)会保存在一个HashTable数据类型的符号表中(symbol_table) ...

  8. poj 2195 Going Home

    /* 做网络流的题建图真的是太重要了! 本题是将人所在的位置和房子所在的位置建立边的联系,其中man到house这一条边的流量为 1, 费用为两者的距离 而方向边的流量为 0, 费用为正向边的相反数( ...

  9. Java多线程系列--“基础篇”05之 线程等待与唤醒

    概要 本章,会对线程等待/唤醒方法进行介绍.涉及到的内容包括:1. wait(), notify(), notifyAll()等方法介绍2. wait()和notify()3. wait(long t ...

  10. Yii2的深入学习--yii\base\Object 类

    之前我们说过 Yii2 中大多数类都继承自 yii\base\Object,今天就让我们来看一下这个类. Object 是一个基础类,实现了属性的功能,其基本内容如下: <?php namesp ...