ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

JDK1.8源码(五)——java.util.Vector类

2021-09-26 18:35:29  阅读:147  来源: 互联网

标签:index JDK1.8 synchronized int elementData util elementCount 源码 public


一、概述

1、介绍

  Java里古老的容器,JDK1.0版本添加的类,矢量队列,线程安全的,使用关键字synchronized,保证方法同步。
  底层维护一个 Object 数组,初始长度为10,默认情况扩容为原来数组的 2 倍。也可以指定扩容步长。其他的和 ArrayList 没有太大区别。
  扩容原理:

2、API的使用

  synchronized boolean add(E object)

  void add(int location, E object)

  synchronized boolean addAll(Collection<? extends E> collection)

  synchronized boolean addAll(int location, Collection<? extends E> collection)

  synchronized void addElement(E object)

  synchronized int capacity()

  void clear()

  synchronized Object clone()

  boolean contains(Object object)

  synchronized boolean containsAll(Collection<?> collection)

  synchronized void copyInto(Object[] elements)

  synchronized E elementAt(int location)

  Enumeration<E> elements()

  synchronized void ensureCapacity(int minimumCapacity)

  synchronized boolean equals(Object object)

  synchronized E firstElement()

  E get(int location)

  synchronized int hashCode()

  synchronized int indexOf(Object object, int location)

  int indexOf(Object object)

  synchronized void insertElementAt(E object, int location)

  synchronized boolean isEmpty()

  synchronized E lastElement()

  synchronized int lastIndexOf(Object object, int location)

  synchronized int lastIndexOf(Object object)

  synchronized E remove(int location)

  boolean remove(Object object)

  synchronized boolean removeAll(Collection<?> collection)

  synchronized void removeAllElements()

  synchronized boolean removeElement(Object object)

  synchronized void removeElementAt(int location)

  synchronized boolean retainAll(Collection<?> collection)

  synchronized E set(int location, E object)

  synchronized void setElementAt(E object, int location)

  synchronized void setSize(int length)

  synchronized int size()

  synchronized List<E> subList(int start, int end)

  synchronized <T> T[] toArray(T[] contents)

  synchronized Object[] toArray()

  synchronized String toString()

  synchronized void trimToSize()

3、四种遍历方式

  ①迭代器

 1 public class Main {
 2     public static void main(String[] args) {
 3         Vector<Integer> vector = new Vector<>();
 4         vector.add(1);
 5         vector.add(3);
 6         vector.add(2);
 7         final Iterator<Integer> iterator = vector.iterator();
 8         while (iterator.hasNext()) {
 9             System.out.println(iterator.next());
10         }
11     }
12 }

  ②随机访问
  由于Vector实现了RandomAccess接口,它支持通过索引值去随机访问元素。

 1 public class Main {
 2     public static void main(String[] args) {
 3         Vector<Integer> vector = new Vector<>();
 4         vector.add(1);
 5         vector.add(3);
 6         vector.add(2);
 7         for (int i = 0; i < vector.size(); i++) {
 8             System.out.println(vector.get(i));
 9         }
10     }
11 }

  ③增强for循环

 1 public class Main {
 2     public static void main(String[] args) {
 3         Vector<Integer> vector = new Vector<>();
 4         vector.add(1);
 5         vector.add(3);
 6         vector.add(2);
 7         for (Integer integer : vector) {
 8             System.out.println(integer);
 9         }
10     }
11 }

  ④Enumeration遍历
  枚举,这也是Vector特有的遍历方式。

 1 public class Main {
 2     public static void main(String[] args) {
 3         Vector<Integer> vector = new Vector<>();
 4         vector.add(1);
 5         vector.add(3);
 6         vector.add(2);
 7         final Enumeration<Integer> elements = vector.elements();
 8         while (elements.hasMoreElements()) {
 9             System.out.println(elements.nextElement());
10         }
11     }
12 }

二、类源码

1、类声明

  源码示例:

 1  * @author  Lee Boynton
 2  * @author  Jonathan Payne
 3  * @see Collection
 4  * @see LinkedList
 5  * @since   JDK1.0
 6  */
 7 public class Vector<E>
 8     extends AbstractList<E>
 9     implements List<E>, RandomAccess, Cloneable, java.io.Serializable
10 {}

  实现了 RandmoAccess 接口,为List提供快速随机访问功能。
  实现了 Cloneable 接口,复写clone()函数,表示它能被克隆。
  实现了 Serializable 接口,标识该类可序列化。

2、类属性

  源码示例:读一下源码中的英文注释。

 1 // 动态数组.默认初始化大小为 10
 2 protected Object[] elementData;
 3 
 4 // 动态数组的实际大小.集合中实际元素的个数
 5 protected int elementCount;
 6 
 7 // 扩容步长.默认为0.若指定了,则按指定长度扩容
 8 protected int capacityIncrement;
 9 
10 // 可序列化的UID号
11 private static final long serialVersionUID = -2767605614048989439L;

3、类构造器

  源码示例:

 1 public Vector(int initialCapacity, int capacityIncrement) {
 2     super();
 3     if (initialCapacity < 0)
 4         throw new IllegalArgumentException("Illegal Capacity: "+
 5                                            initialCapacity);
 6     // 新建一个数组,数组容量是initialCapacity                                 
 7     this.elementData = new Object[initialCapacity];
 8     // 设置扩容步长
 9     this.capacityIncrement = capacityIncrement;
10 }
11 
12 // 默认的扩容步长为 0
13 public Vector(int initialCapacity) {
14     this(initialCapacity, 0);
15 }
16 
17 // 默认构造器初始大小为 10
18 public Vector() {
19     this(10);
20 }
21 
22 public Vector(Collection<? extends E> c) {
23     elementData = c.toArray();
24     // 设置数组长度
25     elementCount = elementData.length;
26     // c.toArray might (incorrectly) not return Object[] (see 6260652)
27     if (elementData.getClass() != Object[].class)
28         elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
29 }

4、add()方法

  源码示例:扩容原理

 1 // 方法是同步的
 2 public synchronized boolean add(E e) {
 3     // 记录修改次数+1
 4     modCount++;
 5     // 判断是否需要扩容
 6     ensureCapacityHelper(elementCount + 1);
 7     // 将新增的元素 e 放到elementData数组中
 8     elementData[elementCount++] = e;
 9     return true;
10 }
11 
12 private void ensureCapacityHelper(int minCapacity) {
13     // overflow-conscious code
14     // 表示需要扩容
15     if (minCapacity - elementData.length > 0)
16         grow(minCapacity);
17 }
18 
19 private void grow(int minCapacity) {
20     // overflow-conscious code
21     int oldCapacity = elementData.length;
22     
23     // 体现出扩容步长.若没设置,则扩容为 两倍
24     int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
25                                      capacityIncrement : oldCapacity);
26     if (newCapacity - minCapacity < 0)
27         newCapacity = minCapacity;
28     if (newCapacity - MAX_ARRAY_SIZE > 0)
29         newCapacity = hugeCapacity(minCapacity);
30         
31     // 通过数组拷贝的方式将原数组的元素拷贝到新的容量中
32     elementData = Arrays.copyOf(elementData, newCapacity);
33 }

5、addElement()方法

  源码示例:

1 // 与add()方法相同
2 public synchronized void addElement(E obj) {
3     modCount++;
4     ensureCapacityHelper(elementCount + 1);
5     elementData[elementCount++] = obj;
6 }

6、get()方法

  源码示例:

1 public synchronized E get(int index) {
2     if (index >= elementCount)
3         throw new ArrayIndexOutOfBoundsException(index);
4 
5     // 通过数组下标获取元素
6     return elementData(index);
7 }

7、insertElementAt()方法

  源码示例:在指定位置插入元素

 1 // 在index位置处插入元素(obj)
 2 public synchronized void insertElementAt(E obj, int index) {
 3     modCount++;
 4     if (index > elementCount) {
 5         throw new ArrayIndexOutOfBoundsException(index
 6                                                  + " > " + elementCount);
 7     }
 8     // 判断是否需要扩容
 9     ensureCapacityHelper(elementCount + 1);
10     // 将数组拷贝
11     System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
12     // 将元素插入到index的位置
13     elementData[index] = obj;
14     elementCount++;
15 }

8、其他方法

  源码示例:

  1 // 将数组Vector的全部元素都拷贝到数组anArray中
  2 public synchronized void copyInto(Object[] anArray) {
  3     System.arraycopy(elementData, 0, anArray, 0, elementCount);
  4 }
  5 
  6 // 将当前容量值设为 实际元素个数
  7 public synchronized void trimToSize() {
  8     modCount++;
  9     int oldCapacity = elementData.length;
 10     if (elementCount < oldCapacity) {
 11         // 将数组的元素全部拷贝到实际容量大小的数组中去
 12         elementData = Arrays.copyOf(elementData, elementCount);
 13     }
 14 }
 15 
 16 // 确定Vector的容量。
 17 public synchronized void ensureCapacity(int minCapacity) {
 18     if (minCapacity > 0) {
 19         modCount++;
 20         ensureCapacityHelper(minCapacity);
 21     }
 22 }
 23 
 24 // 设置容量值为 newSize
 25 public synchronized void setSize(int newSize) {
 26     modCount++;
 27     if (newSize > elementCount) {
 28         // 调整Vector的大小
 29         ensureCapacityHelper(newSize);
 30     } else {
 31         // 将从 newSize 位置开始的元素都设置为null
 32         for (int i = newSize ; i < elementCount ; i++) {
 33             elementData[i] = null;
 34         }
 35     }
 36     elementCount = newSize;
 37 }
 38 
 39 // 返回Vector总容量大小
 40 public synchronized int capacity() {
 41     return elementData.length;
 42 }
 43 
 44 // 返回Vector中实际元素个数
 45 public synchronized int size() {
 46     return elementCount;
 47 }
 48 
 49 // 判断Vector是否为空
 50 public synchronized boolean isEmpty() {
 51     return elementCount == 0;
 52 }
 53 
 54 // 返回Vector中全部元素对应的Enumeration
 55 public Enumeration<E> elements() {
 56     return new Enumeration<E>() {
 57         int count = 0;
 58         // 是否存在下一个元素
 59         public boolean hasMoreElements() {
 60             return count < elementCount;
 61         }
 62         // 获取下一个元素
 63         public E nextElement() {
 64             synchronized (Vector.this) {
 65                 if (count < elementCount) {
 66                     return elementData(count++);
 67                 }
 68             }
 69             throw new NoSuchElementException("Vector Enumeration");
 70         }
 71     };
 72 }
 73 
 74 // 是否包含对象(o)
 75 public boolean contains(Object o) {
 76     return indexOf(o, 0) >= 0;
 77 }
 78 
 79 // 从 0 开始搜索 o
 80 public int indexOf(Object o) {
 81     return indexOf(o, 0);
 82 }
 83 
 84 // 从 index 开始搜索 o
 85 public synchronized int indexOf(Object o, int index) {
 86     if (o == null) {
 87         // 搜索 o == null 的情况
 88         for (int i = index ; i < elementCount ; i++)
 89             if (elementData[i]==null)
 90                 return i;
 91     } else {
 92         // 若 o!=null 搜索 o 返回对应的索引
 93         for (int i = index ; i < elementCount ; i++)
 94             if (o.equals(elementData[i]))
 95                 return i;
 96     }
 97     // 找不到,返回 -1
 98     return -1;
 99 }
100 
101 // 从后向前查找元素(o)。并返回元素的索引
102 public synchronized int lastIndexOf(Object o) {
103     return lastIndexOf(o, elementCount - 1);
104 }
105 
106 // 从后向前查找元素(o)。开始位置是从前向后的第index个数;
107 public synchronized int lastIndexOf(Object o, int index) {
108     if (index >= elementCount)
109         throw new IndexOutOfBoundsException(index + " >= " + elementCount);
110 
111     if (o == null) {
112         // 若查找元素为null,则反向找出null元素,并返回它对应的序号
113         for (int i = index; i >= 0; i--)
114             if (elementData[i] == null)
115                 return i;
116     } else {
117         // 若查找元素不为null,则反向找出该元素,并返回它对应的序号
118         for (int i = index; i >= 0; i--)
119             if (o.equals(elementData[i]))
120                 return i;
121     }
122     // 找不到,返回 -1
123     return -1;
124 }
125 
126 // 返回index位置的元素。
127 public synchronized E elementAt(int index) {
128     // index越界.抛出异常
129     if (index >= elementCount) {
130         throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
131     }
132 
133     return elementData(index);
134 }
135 
136 // 获取第一个元素。
137 public synchronized E firstElement() {
138     if (elementCount == 0) {
139         throw new NoSuchElementException();
140     }
141     return elementData(0);
142 }
143 
144 // 获取最后一个元素。
145 public synchronized E lastElement() {
146     if (elementCount == 0) {
147         throw new NoSuchElementException();
148     }
149     return (E) elementData[elementCount - 1];
150 }
151 
152 // 设置index位置的元素值为obj
153 public synchronized void setElementAt(E obj, int index) {
154     if (index >= elementCount) {
155         throw new ArrayIndexOutOfBoundsException(index + " >= " +
156                 elementCount);
157     }
158     elementData[index] = obj;
159 }
160 
161 // 删除index位置的元素
162 public synchronized void removeElementAt(int index) {
163     modCount++;
164     if (index >= elementCount) {
165         throw new ArrayIndexOutOfBoundsException(index + " >= " +
166                                                  elementCount);
167     }
168     else if (index < 0) {
169         throw new ArrayIndexOutOfBoundsException(index);
170     }
171     int j = elementCount - index - 1;
172     if (j > 0) {
173         System.arraycopy(elementData, index + 1, elementData, index, j);
174     }
175     elementCount--;
176     elementData[elementCount] = null; /* to let gc do its work */
177 }
178 
179 // 在Vector中查找并删除元素obj。
180 public synchronized boolean removeElement(Object obj) {
181     modCount++;
182     // 找到 obj
183     int i = indexOf(obj);
184     if (i >= 0) {
185         // 存在,移除,返回true
186         removeElementAt(i);
187         return true;
188     }
189     // 失败,返回false
190     return false;
191 }
192 
193 // 删除Vector中的全部元素
194 public synchronized void removeAllElements() {
195     modCount++;
196     // Let gc do its work
197     // 将Vector中的全部元素设为null
198     for (int i = 0; i < elementCount; i++)
199         elementData[i] = null;
200 
201     elementCount = 0;
202 }
203 
204 // 克隆函数
205 public synchronized Object clone() {
206     try {
207         @SuppressWarnings("unchecked")
208             Vector<E> v = (Vector<E>) super.clone();
209         // 将当前Vector的全部元素拷贝到v中
210         v.elementData = Arrays.copyOf(elementData, elementCount);
211         v.modCount = 0;
212         return v;
213     } catch (CloneNotSupportedException e) {
214         // this shouldn't happen, since we are Cloneable
215         throw new InternalError(e);
216     }
217 }
218 
219 // 返回将vector转化为Object数组
220 public synchronized Object[] toArray() {
221     return Arrays.copyOf(elementData, elementCount);
222 }
223 
224 // 返回Vector的模板数组。所谓模板数组,即可以将T设为任意的数据类型
225 public synchronized <T> T[] toArray(T[] a) {
226     // 若数组a的大小 < Vector的元素个数;
227     // 则新建一个T[]数组,数组大小是“Vector的元素个数”,并将“Vector”全部拷贝到新数组中
228     if (a.length < elementCount)
229         return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
230 
231     // 若数组a的大小 >= Vector的元素个数;
232     // 则将Vector的全部元素都拷贝到数组a中。
233     System.arraycopy(elementData, 0, a, 0, elementCount);
234 
235     if (a.length > elementCount)
236         a[elementCount] = null;
237 
238     return a;
239 }
240 
241 // 设置index位置的值为element。并返回index位置的原始值
242 public synchronized E set(int index, E element) {
243     if (index >= elementCount)
244         throw new ArrayIndexOutOfBoundsException(index);
245 
246     Object oldValue = elementData[index];
247     elementData[index] = element;
248     return (E) oldValue;
249 }
250 
251 // 删除Vector中的元素o
252 public boolean remove(Object o) {
253     return removeElement(o);
254 }
255 
256 // 删除index位置的元素,并返回index位置的原始值
257 public synchronized E remove(int index) {
258     modCount++;
259     if (index >= elementCount)
260         throw new ArrayIndexOutOfBoundsException(index);
261     // 找到元素    
262     Object oldValue = elementData[index];
263 
264     int numMoved = elementCount - index - 1;
265     if (numMoved > 0)
266         System.arraycopy(elementData, index + 1, elementData, index,
267                 numMoved);
268     elementData[--elementCount] = null; // Let gc do its work
269 
270     return (E) oldValue;
271 }
272 
273 // 清空Vector
274 public void clear() {
275     removeAllElements();
276 }
277 
278 // 返回Vector是否包含集合c
279 public synchronized boolean containsAll(Collection<?> c) {
280     return super.containsAll(c);
281 }
282 
283 // 将集合c添加到Vector中
284 public synchronized boolean addAll(Collection<? extends E> c) {
285     modCount++;
286     Object[] a = c.toArray();
287     int numNew = a.length;
288     ensureCapacityHelper(elementCount + numNew);
289     // 将集合c的全部元素拷贝到数组elementData中
290     System.arraycopy(a, 0, elementData, elementCount, numNew);
291     elementCount += numNew;
292     return numNew != 0;
293 }
294 
295 // 删除集合c的全部元素
296 public synchronized boolean removeAll(Collection<?> c) {
297     return super.removeAll(c);
298 }
299 
300 // 删除“非集合c中的元素”
301 public synchronized boolean retainAll(Collection<?> c) {
302     return super.retainAll(c);
303 }
304 
305 // 从index位置开始,将集合c添加到Vector中
306 public synchronized boolean addAll(int index, Collection<? extends E> c) {
307     modCount++;
308     if (index < 0 || index > elementCount)
309         throw new ArrayIndexOutOfBoundsException(index);
310 
311     Object[] a = c.toArray();
312     int numNew = a.length;
313     ensureCapacityHelper(elementCount + numNew);
314 
315     int numMoved = elementCount - index;
316     if (numMoved > 0)
317         System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
318 
319     System.arraycopy(a, 0, elementData, index, numNew);
320     elementCount += numNew;
321     return numNew != 0;
322 }
323 
324 // 返回两个对象是否相等
325 public synchronized boolean equals(Object o) {
326     return super.equals(o);
327 }
328 
329 // 计算哈希值
330 public synchronized int hashCode() {
331     return super.hashCode();
332 }
333 
334 // 调用父类的toString()
335 public synchronized String toString() {
336     return super.toString();
337 }
338 
339 // 获取[fromIndex,toIndex)子列表,同步的
340 public synchronized List<E> subList(int fromIndex, int toIndex) {
341     return Collections.synchronizedList(super.subList(fromIndex, toIndex),
342                                         this);
343 }
344 
345 
346 // 删除Vector中fromIndex到toIndex的元素
347 protected synchronized void removeRange(int fromIndex, int toIndex) {
348     modCount++;
349     // 新的长度
350     int numMoved = elementCount - toIndex;
351     // 底层拷贝
352     System.arraycopy(elementData, toIndex, elementData, fromIndex,
353                      numMoved);
354 
355     // Let gc do its work
356     int newElementCount = elementCount - (toIndex-fromIndex);
357     while (elementCount != newElementCount)
358         elementData[--elementCount] = null;
359 }
360 
361 // java.io.Serializable的写入函数.用于序列化
362 private void writeObject(java.io.ObjectOutputStream s)
363         throws java.io.IOException {
364     final java.io.ObjectOutputStream.PutField fields = s.putFields();
365     final Object[] data;
366     synchronized (this) {
367         fields.put("capacityIncrement", capacityIncrement);
368         fields.put("elementCount", elementCount);
369         data = elementData.clone();
370     }
371     fields.put("elementData", data);
372     s.writeFields();
373 }

标签:index,JDK1.8,synchronized,int,elementData,util,elementCount,源码,public
来源: https://www.cnblogs.com/originator/p/15337338.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有