前言
从最初的迭代器,到接口、到抽象类、到 ArrayList 实现类,我们已经完整阅读过一个实现类的来龙去脉了。相信大家已经拥有了自己阅读源代码的能力。
今天我们继续来学习另一个实现类 Vector
Vector 类
The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.
Vector 类是一个实现了动态数组的对象。像数组一样,它可以用索引进行访问。然而,Vector 在创建后,可以根据需要自动扩容或者缩容。
Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector’s storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.
每个 vector 都尝试通过维护一个 capacity 和一个 capacityIncrement 来优化存储。capacity 至少是 size 的大小。一般是比 size 大,因为在添加元素时,vector 会以 capacityIncrement 的大小成块增加容量。程序在添加大量元素时,可以先增加容量,以免频繁扩容。
The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the vector is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. The Enumerations returned by the elements method are not fail-fast; if the Vector is structurally modified at any time after the enumeration is created then the results of enumerating are undefined.
这个类返回的 iterator 和 listIterator 是快速失败的:如果 vector 在创建后存在除了自己的 remove 和 add 以外的任何结构性修改,迭代器会抛出并发修改异常。因此,面对并发修改时,迭代器会快速、明确地失败而不是冒着风险继续。 返回的 Enumerations(之前讲过,迭代器的前身) 不是快速失败的。如果存在并发修改,enumeration 的行为是未知的。
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
注意,快速失败无法保证安全性,正常来说,没有同步的并发修改是不可能完全保证安全的。快速失败是尽最大努力抛出异常,因此不要依赖于这个异常来写代码,快速失败只是用来检测 bug 的。
As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use {@link ArrayList} in place of Vector.
Java 1.2版本,这个类被改造为实现 List 接口,成为集合框架的一员。和新的集合实现不同,Vector 是同步的。如果不需要线程安全,推荐使用 ArrayList
@param Type of component elements
@author Lee Boynton
@author Jonathan Payne
@see Collection
@see LinkedList
@since 1.0
属性
elementData
The array buffer into which the components of the vector are stored. The capacity of the vector is the length of this array buffer, and is at least large enough to contain all the vector’s elements.
这个数组就是 vector 存储元素的缓冲区。容量至少要可以包含全部的元素。
Any array elements following the last element in the Vector are null.
数组最后一个元素之后都是 null。
@serial 这个是序列化的标记,说明可以序列化。
这个数组就是用来存数据的,和 ArrayList 同理。
@SuppressWarnings("serial") // Conditionally serializable
protected Object[] elementData;
elementCount
The number of valid components in this Vector object. Components elementData[0] through elementData[elementCount-1] are the actual items.
vector 内部有效元素的数量。 elementData[0] 到elementData[elementCount - 1] 是实际的元素。
其实就是 size。vector 是 java 1.0 就有的,因此写法是和 集合不一样的,英文中也不管里面的东西叫元素,而是叫 component。
@serial
protected int elementCount;
capacityIncrement
The amount by which the capacity of the vector is automatically incremented when its size becomes greater than its capacity. If the capacity increment is less than or equal to zero, the capacity of the vector is doubled each time it needs to grow.
每次自动扩容的大小。如果这个大小 <= 0,那么每次扩容扩二倍。
@serial
protected int capacityIncrement;
serialVersionUID
@java.io.Serial
private static final long serialVersionUID = -2767605614048989439L;
方法
Vector
Constructs an empty vector with the specified initial capacity and capacity increment.
创建一个拥有初始容量容量增量的空 vector。
@param initialCapacity the initial capacity of the vector
@param capacityIncrement the amount by which the capacity is
increased when the vector overflows
@throws IllegalArgumentException if the specified initial capacity
is negative
public Vector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
Vector
Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero.
创建空 vector,指定初始容量为,增量为 0
@param initialCapacity the initial capacity of the vector
@throws IllegalArgumentException if the specified initial capacity
is negative
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
Vector
Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero.
初始容量为 10,增量为 0
public Vector() {
this(10);
}
Vector
Constructs a vector containing the elements of the specified collection, in the order they are returned by the collection’s iterator.
根据指定集合创建 vector,按照指定集合的迭代器遍历顺序。
可以看到是 1.2 才有的,那时候是出现 集合 的版本。
@param c the collection whose elements are to be placed into this
vector
@throws NullPointerException if the specified collection is null
@since 1.2
public Vector(Collection<? extends E> c) {
Object[] a = c.toArray();
elementCount = a.length;
if (c.getClass() == ArrayList.class) {
elementData = a;
} else {
elementData = Arrays.copyOf(a, elementCount, Object[].class);
}
}
copyInto
Copies the components of this vector into the specified array. The item at index k in this vector is copied into component k of anArray.
拷贝到指定数组中,索引不变
@param anArray the array into which the components get copied
@throws NullPointerException if the given array is null
@throws IndexOutOfBoundsException if the specified array is not
large enough to hold all the components of this vector
@throws ArrayStoreException if a component of this vector is not of
a runtime type that can be stored in the specified array
@see #toArray(Object[])
其实就是 toArray 方法啦。
public synchronized void copyInto(Object[] anArray) {
System.arraycopy(elementData, 0, anArray, 0, elementCount);
}
trimToSize
Trims the capacity of this vector to be the vector’s current size. If the capacity of this vector is larger than its current size, then the capacity is changed to equal the size by replacing its internal data array, kept in the field elementData, with a smaller one. An application can use this operation to minimize the storage of a vector.
将多余容量去除。
就是给容量变成了 size 的大小,节约内存。现代计算机好像不那么需要。
public synchronized void trimToSize() {
modCount++;
int oldCapacity = elementData.length;
if (elementCount < oldCapacity) {
elementData = Arrays.copyOf(elementData, elementCount);
}
}
ensureCapacity
Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.
如果有必要,则增加容量,确保至少可以容纳指定参数的元素。
这个和 ArrayList 是一样的。
这个方法供其他方法进行调用的,比如说我要放入 20 个元素进去,那么就调用并传入参数 size + 20,意思就是原来的加上20,必须确保够用。调用这个方法就可以确保容量够用。
If the current capacity of this vector is less than minCapacity, then its capacity is increased by replacing its internal data array, kept in the field elementData, with a larger one. The size of the new data array will be the old size plus capacityIncrement, unless the value of capacityIncrement is less than or equal to zero, in which case the new capacity will be twice the old capacity; but if this new size is still smaller than minCapacity, then the new capacity will be minCapacity.
如果当前容量小于 指定的最小值,就扩容,加上 增量大小。增量大小是 <= 0, 扩二倍。如果新的大小仍然小于 指定最小大小,那么就扩容到 指定大小。
意思就是先按增量扩容,扩完不行就直接扩到指定最小值。
@param minCapacity the desired minimum capacity
public synchronized void ensureCapacity(int minCapacity) {
if (minCapacity > 0) {
modCount++;
if (minCapacity > elementData.length)
grow(minCapacity);
}
}
grow
Increases the capacity to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
增加容量到能装下指定容量的元素。
内部实现逻辑使用了 ArraysSupport.newLength 方法,这是 java 9 引进的动态数组扩容方法。第一个参数是旧数组容量,第二个参数是最小容量,第三个参数是优选容量。
也就是上个方法提到的,如果旧容量够不扩容,不够优先进行二倍扩容,不行就直接扩到 指定容量。
@param minCapacity the desired minimum capacity
@throws OutOfMemoryError if minCapacity is less than zero
private Object[] grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = ArraysSupport.newLength(oldCapacity,
minCapacity - oldCapacity, /* minimum growth */
capacityIncrement > 0 ? capacityIncrement : oldCapacity
/* preferred growth */);
return elementData = Arrays.copyOf(elementData, newCapacity);
}
grow
扩容+1. 在 插入 或者 add 的时候用。
private Object[] grow() {
return grow(elementCount + 1);
}
setSize
Sets the size of this vector. If the new size is greater than the current size, new null items are added to the end of the vector. If the new size is less than the current size, all components at index newSize and greater are discarded.
设置大小。如果设置的大小比当前大,则后面的全置为 null。如果比当前小,则 newSize 索引处以及后面全部丢弃。
经过测试,setSize如果将 size 变小,容量是不变的。比如原来是 12345,容量是5,setSize(3),现在就剩123,容量还是5,并且后面是 null,而且 null 不会作为元素显示出来。开头类的描述里面说了,里面的元素是 null 之前的元素。
@param newSize the new size of this vector
@throws ArrayIndexOutOfBoundsException if the new size is negative
public synchronized void setSize(int newSize) {
modCount++;
if (newSize > elementData.length)
grow(newSize);
final Object[] es = elementData;
for (int to = elementCount, i = newSize; i < to; i++)
es[i] = null;
elementCount = newSize;
}
capacity
Returns the current capacity of this vector.
返回容量
@return the current capacity (the length of its internal
data array, kept in the field elementData of this vector)
public synchronized int capacity() {
return elementData.length;
}
size
Returns the number of components in this vector.
返回 size
这里可以看到有 elementCount。其实就是集合的size,之前这么写了,现在也不改了,但是因为是集合框架中的一员,实现了 List 接口,因此必须有这个方法。
@return the number of components in this vector
public synchronized int size() {
return elementCount;
}
isEmpty
Tests if this vector has no components.
是否为空
@return true if and only if this vector has
no components, that is, its size is zero; false otherwise.
public synchronized boolean isEmpty() {
return elementCount == 0;
}
elements
Returns an enumeration of the components of this vector. The returned Enumeration object will generate all items in this vector. The first item generated is the item at index 0, then the item at index 1, and so on. If the vector is structurally modified while enumerating over the elements then the results of enumerating are undefined.
返回 Enumeration,就是旧版本的迭代器。
@return an enumeration of the components of this vector
@see Iterator
public Enumeration<E> elements() {
return new Enumeration<E>() {
int count = 0;
public boolean hasMoreElements() {
return count < elementCount;
}
public E nextElement() {
synchronized (Vector.this) {
if (count < elementCount) {
return elementData(count++);
}
}
throw new NoSuchElementException("Vector Enumeration");
}
};
}
contains
Returns true if this vector contains the specified element. More formally, returns true if and only if this vector contains at least one element e such that Objects.equals(o, e).
是否包含某个元素。
这里使用了 indexOf 方法,这个和 ArrayList 还不同,传入两个参数,一个是搜索的对象,一个是搜索的起始位置。
@param o element whose presence in this vector is to be tested
@return true if this vector contains the specified element
public boolean contains(Object o) {
return indexOf(o, 0) >= 0;
}
indexOf
Returns the index of the first occurrence of the specified element in this vector, or -1 if this vector does not contain the element. More formally, returns the lowest index i such that Objects.equals(o, get(i)), or -1 if there is no such index.
这个是正常的 indexOf,传入对象返回索引。
@param o element to search for
@return the index of the first occurrence of the specified element in
this vector, or -1 if this vector does not contain the element
public int indexOf(Object o) {
return indexOf(o, 0);
}
indexOf
Returns the index of the first occurrence of the specified element in this vector, searching forwards from index, or returns -1 if the element is not found. More formally, returns the lowest index i such that (i >= index && Objects.equals(o, get(i))), or -1 if there is no such index.
从指定索引开始搜索对象。
@param o element to search for
@param index index to start searching from
@return the index of the first occurrence of the element in
this vector at position index or later in the vector; -1 if the element is not found.
@throws IndexOutOfBoundsException if the specified index is negative@see Object#equals(Object)
public synchronized int indexOf(Object o, int index) {
if (o == null) {
for (int i = index ; i < elementCount ; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = index ; i < elementCount ; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
lastIndexOf
Returns the index of the last occurrence of the specified element in this vector, or -1 if this vector does not contain the element. More formally, returns the highest index i such that Objects.equals(o, get(i)), or -1 if there is no such index.
返回最后一个对象的索引
@param o element to search for
@return the index of the last occurrence of the specified element in
this vector, or -1 if this vector does not contain the element
public synchronized int lastIndexOf(Object o) {
return lastIndexOf(o, elementCount-1);
}
lastIndexOf
Returns the index of the last occurrence of the specified element in this vector, searching backwards from index, or returns -1 if the element is not found. More formally, returns the highest index i such that (i <= index && Objects.equals(o, get(i))), or -1 if there is no such index.
指定位置搜索,返回最后一个对象的索引。
这个是由后往前搜索,也就是指定索引作为末尾,出现的最后一个对象。而 IndexOf 是指定位置往后,第一个对象。
@param o element to search for
@param index index to start searching backwards from
@return the index of the last occurrence of the element at position
less than or equal to index in this vector; -1 if the element is not found.
@throws IndexOutOfBoundsException if the specified index is greater
than or equal to the current size of this vector
public synchronized int lastIndexOf(Object o, int index) {
if (index >= elementCount)
throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
if (o == null) {
for (int i = index; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = index; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
elementAt
Returns the component at the specified index.
This method is identical in functionality to the {@link #get(int)} method (which is part of the List interface).
返回指定位置的元素。
这个方法和 get 方法一样。
历史遗留问题,以前没 List 接口。所以不叫 get
@param index an index into this vector
@return the component at the specified index
@throws ArrayIndexOutOfBoundsException if the index is out of range
(index < 0 || index >= size())
public synchronized E elementAt(int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
}
return elementData(index);
}
firstElement
Returns the first component (the item at index 0) of this vector.
返回第一个元素
@return the first component of this vector
@throws NoSuchElementException if this vector has no components
public synchronized E firstElement() {
if (elementCount == 0) {
throw new NoSuchElementException();
}
return elementData(0);
}
lastElement
Returns the last component of the vector.
返回最后一个元素
@return the last component of the vector, i.e., the component at index
size() - 1
@throws NoSuchElementException if this vector is empty
public synchronized E lastElement() {
if (elementCount == 0) {
throw new NoSuchElementException();
}
return elementData(elementCount - 1);
}
setElementAt
Sets the component at the specified index of this vector to be the specified object. The previous component at that position is discarded.
指定位置设置为指定对象,以前的对象丢弃。
The index must be a value greater than or equal to 0 and less than the current size of the vector.
索引必须大于等于0.
This method is identical in functionality to the {@link #set(int, Object) set(int, E)} method (which is part of the List interface). Note that the set method reverses the order of the parameters, to more closely match array usage. Note also that the set method returns the old value that was stored at the specified position.
和 set 方法完全一样。注意 set 的参数是反着的,更符合数组的用法。注意 set 会返回旧数值。
@param obj what the component is to be set to
@param index the specified index
@throws ArrayIndexOutOfBoundsException if the index is out of range
(index < 0 || index >= size())
public synchronized void setElementAt(E obj, int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
elementData[index] = obj;
}
removeElementAt
Deletes the component at the specified index. Each component in this vector with an index greater or equal to the specified index is shifted downward to have an index one smaller than the value it had previously. The size of this vector is decreased by 1.
删除指定位置的元素。并且其他数会索引-1。size -1.
The index must be a value greater than or equal to 0 and less than the current size of the vector.
索引必须大于等于 0,小于等于 size。
This method is identical in functionality to the {@link #remove(int)} method (which is part of the List interface). Note that the remove method returns the old value that was stored at the specified position.
和 remove 方法一样,但是 remove 会返回旧值。
@param index the index of the object to remove
@throws ArrayIndexOutOfBoundsException if the index is out of range
(index < 0 || index >= size())
public synchronized void removeElementAt(int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
else if (index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
int j = elementCount - index - 1;
if (j > 0) {
System.arraycopy(elementData, index + 1, elementData, index, j);
}
modCount++;
elementCount--;
elementData[elementCount] = null; /* to let gc do its work */
}
insertElementAt
Inserts the specified object as a component in this vector at the specified index. Each component in this vector with an index greater or equal to the specified index is shifted upward to have an index one greater than the value it had previously.
插入元素,后面的元素向右移动
The index must be a value greater than or equal to 0 and less than or equal to the current size of the vector. (If the index is equal to the current size of the vector, the new element is appended to the Vector.)
索引大于等于0,小于等于 size,如果等于 size ,在末尾添加元素。
This method is identical in functionality to the {@link #add(int, Object) add(int, E)} method (which is part of the List interface). Note that the add method reverses the order of the parameters, to more closely match array usage.
和 add 一样,但反转了参数顺序。
@param obj the component to insert
@param index where to insert the new component
@throws ArrayIndexOutOfBoundsException if the index is out of range
(index < 0 || index > size())
public synchronized void insertElementAt(E obj, int index) {
if (index > elementCount) {
throw new ArrayIndexOutOfBoundsException(index
+ " > " + elementCount);
}
modCount++;
final int s = elementCount;
Object[] elementData = this.elementData;
if (s == elementData.length)
elementData = grow();
System.arraycopy(elementData, index,
elementData, index + 1,
s - index);
elementData[index] = obj;
elementCount = s + 1;
}
addElement
Adds the specified component to the end of this vector, increasing its size by one. The capacity of this vector is increased if its size becomes greater than its capacity.
末尾添加元素
This method is identical in functionality to the {@link #add(Object) add(E)} method (which is part of the List interface).
@param obj the component to be added
public synchronized void addElement(E obj) {
modCount++;
add(obj, elementData, elementCount);
}
removeElement
Removes the first (lowest-indexed) occurrence of the argument from this vector. If the object is found in this vector, each component in the vector with an index greater or equal to the object’s index is shifted downward to have an index one smaller than the value it had previously.
删除第一个出现的指定元素。
This method is identical in functionality to the {@link #remove(Object)} method (which is part of the List interface).
@param obj the component to be removed
@return true if the argument was a component of this
vector; false otherwise.
public synchronized boolean removeElement(Object obj) {
modCount++;
int i = indexOf(obj);
if (i >= 0) {
removeElementAt(i);
return true;
}
return false;
}
removeAllElements
Removes all components from this vector and sets its size to zero.
删除所有元素
This method is identical in functionality to the clear method (which is part of the List interface).
public synchronized void removeAllElements() {
final Object[] es = elementData;
for (int to = elementCount, i = elementCount = 0; i < to; i++)
es[i] = null;
modCount++;
}
clone
Returns a clone of this vector. The copy will contain a reference to a clone of the internal data array, not a reference to the original internal data array of this Vector object.
浅拷贝。就是说,里面的数组是新的,你可以删除、添加元素之类的,不会影响原数组。但是对对象的引用是原来的。
@return a clone of this vector
public synchronized Object clone() {
try {
@SuppressWarnings("unchecked")
Vector<E> v = (Vector<E>) super.clone();
v.elementData = Arrays.copyOf(elementData, elementCount);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
toArray
Returns an array containing all of the elements in this Vector in the correct order.
转换为数组
@since 1.2
public synchronized Object[] toArray() {
return Arrays.copyOf(elementData, elementCount);
}
toArray
Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array. If the Vector fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this Vector.
放入指定数组,如果空间不够,会重新申请一个数组。
If the Vector fits in the specified array with room to spare (i.e., the array has more elements than the Vector), the element in the array immediately following the end of the Vector is set to null. (This is useful in determining the length of the Vector only if the caller knows that the Vector does not contain any null elements.)
如果 Vector 可以放入指定数组中并且还有剩余空间(即数组的元素多于 Vector),则数组中紧跟 Vector 末尾的元素将设置为 null。(仅当调用者知道 Vector 不包含任何 null 元素时,这才有助于确定 Vector 的长度。)
@param type of array elements. The same type as or a
supertype of .
@param a the array into which the elements of the Vector are to
be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
@return an array containing the elements of the Vector@throws ArrayStoreException if the runtime type of a, , is not
a supertype of the runtime type, , of every element in this Vector
@throws NullPointerException if the given array is null@since 1.2
@SuppressWarnings("unchecked")
public synchronized T[] toArray(T[] a) {
if (a.length < elementCount)
return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
System.arraycopy(elementData, 0, a, 0, elementCount);
if (a.length > elementCount)
a[elementCount] = null;
return a;
}
elementData
@SuppressWarnings("unchecked") E elementData(int index) {
return (E) elementData[index];
}
elementAt
@SuppressWarnings("unchecked")
static E elementAt(Object[] es, int index) {
return (E) es[index];
}
get
Returns the element at the specified position in this Vector.
@param index index of the element to return
@return object at the specified index
@throws ArrayIndexOutOfBoundsException if the index is out of range
(index < 0 || index >= size())
@since 1.2
public synchronized E get(int index) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
return elementData(index);
}
set
Replaces the element at the specified position in this Vector with the specified element.
@param index index of the element to replace
@param element element to be stored at the specified position
@return the element previously at the specified position
@throws ArrayIndexOutOfBoundsException if the index is out of range
(index < 0 || index >= size())
@since 1.2
public synchronized E set(int index, E element) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
add
This helper method split out from add(E) to keep method bytecode size under 35 (the -XX:MaxInlineSize default value), which helps when add(E) is called in a C1-compiled loop.
辅助方法,可以使字节码大小保持在35一下(这是jvm默认参数),这在 C1 编译器很有用。
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length)
elementData = grow();
elementData[s] = e;
elementCount = s + 1;
}
add
Appends the specified element to the end of this Vector.
末尾添加元素
@param e element to be appended to this Vector
@return true (as specified by add)
@since 1.2
public synchronized boolean add(E e) {
modCount++;
add(e, elementData, elementCount);
return true;
}
remove
Removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that Objects.equals(o, get(i)) (if such an element exists).
删除第一个出现的元素
@param o element to be removed from this Vector, if present
@return true if the Vector contained the specified element
@since 1.2
public boolean remove(Object o) {
return removeElement(o);
}
add
Inserts the specified element at the specified position in this Vector. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
指定位置添加元素
@param index index at which the specified element is to be inserted
@param element element to be inserted
@throws ArrayIndexOutOfBoundsException if the index is out of range
(index < 0 || index > size())
@since 1.2
public void add(int index, E element) {
insertElementAt(element, index);
}
remove
Removes the element at the specified position in this Vector. Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the Vector.
删除元素
@param index the index of the element to be removed
@return element that was removed
@throws ArrayIndexOutOfBoundsException if the index is out of range
(index < 0 || index >= size())
@since 1.2
public synchronized E remove(int index) {
modCount++;
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
E oldValue = elementData(index);
int numMoved = elementCount - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--elementCount] = null; // Let gc do its work
return oldValue;
}
clear
Removes all of the elements from this Vector. The Vector will be empty after this call returns (unless it throws an exception).
清空
@since 1.2
public void clear() {
removeAllElements();
}
containsAll
Returns true if this Vector contains all of the elements in the specified Collection.
是否包含指定集合的全部元素
@param c a collection whose elements will be tested for containment
in this Vector
@return true if this Vector contains all of the elements in the
specified collection
@throws NullPointerException if the specified collection is null
public synchronized boolean containsAll(Collection<?> c) {
return super.containsAll(c);
}
addAll
Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned by the specified Collection’s Iterator. The behavior of this operation is undefined if the specified Collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified Collection is this Vector, and this Vector is nonempty.)
添加全部元素到 vector 末尾。如果过程中修改了指定集合,则行为是未定义的。
@param c elements to be inserted into this Vector
@return true if this Vector changed as a result of the call
@throws NullPointerException if the specified collection is null
@since 1.2
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
modCount++;
int numNew = a.length;
if (numNew == 0)
return false;
synchronized (this) {
Object[] elementData = this.elementData;
final int s = elementCount;
if (numNew > elementData.length - s)
elementData = grow(s + numNew);
System.arraycopy(a, 0, elementData, s, numNew);
elementCount = s + numNew;
return true;
}
}
removeAll
Removes from this Vector all of its elements that are contained in the specified Collection.
删除指定元素全部内容
@param c a collection of elements to be removed from the Vector
@return true if this Vector changed as a result of the call
@throws ClassCastException if the types of one or more elements
in this vector are incompatible with the specified collection (optional)
@throws NullPointerException if this vector contains one or more null
elements and the specified collection does not support null elements (optional), or if the specified collection is null
@since 1.2
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return bulkRemove(e -> c.contains(e));
}
retainAll
Retains only the elements in this Vector that are contained in the specified Collection. In other words, removes from this Vector all of its elements that are not contained in the specified Collection.
保留指定集合的元素,其他元素删除。
@param c a collection of elements to be retained in this Vector
(all other elements are removed)
@return true if this Vector changed as a result of the call@throws ClassCastException if the types of one or more elements
in this vector are incompatible with the specified collection (optional)
@throws NullPointerException if this vector contains one or more null
elements and the specified collection does not support null elements (optional), or if the specified collection is null
@since 1.2
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return bulkRemove(e -> !c.contains(e));
}
removeIf
@throws NullPointerException {@inheritDoc}
@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
return bulkRemove(filter);
}
nBits
返回一个能够存储 n 位数据的元素。这里是使用了 long 数组来存储,long 是64 位的,>> 6 意味着除以64。
private static long[] nBits(int n) {
return new long[((n - 1) >> 6) + 1];
}
setBit
和上个方法配合使用。就是将哪一位设置为 1.
private static void setBit(long[] bits, int i) {
bits[i >> 6] |= 1L << i;
}
isClear
判断某位是否位 0
private static boolean isClear(long[] bits, int i) {
return (bits[i >> 6] & (1L << i)) == 0;
}
bulkRemove
批量删除。通过过滤器实现的,函数式编程,前几期讲过。
其中有一个多线程的设计。
private synchronized boolean bulkRemove(Predicate<? super E> filter) {
int expectedModCount = modCount;
final Object[] es = elementData;
final int end = elementCount;
int i;
// Optimize for initial run of survivors
for (i = 0; i < end && !filter.test(elementAt(es, i)); i++)
;
// Tolerate predicates that reentrantly access the collection for
// read (but writers still get CME), so traverse once to find
// elements to delete, a second pass to physically expunge.
if (i < end) {
final int beg = i;
final long[] deathRow = nBits(end - beg);
deathRow[0] = 1L; // set bit 0
for (i = beg + 1; i < end; i++)
if (filter.test(elementAt(es, i)))
setBit(deathRow, i - beg);
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
modCount++;
int w = beg;
for (i = beg; i < end; i++)
if (isClear(deathRow, i - beg))
es[w++] = es[i];
for (i = elementCount = w; i < end; i++)
es[i] = null;
return true;
} else {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
return false;
}
}
addAll
Inserts all of the elements in the specified Collection into this Vector at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the Vector in the order that they are returned by the specified Collection’s iterator.
添加全部元素
@param index index at which to insert the first element from the
specified collection
@param c elements to be inserted into this Vector@return true if this Vector changed as a result of the call
@throws ArrayIndexOutOfBoundsException if the index is out of range
(index < 0 || index > size())
@throws NullPointerException if the specified collection is null@since 1.2
public synchronized boolean addAll(int index, Collection<? extends E> c) {
if (index < 0 || index > elementCount)
throw new ArrayIndexOutOfBoundsException(index);
Object[] a = c.toArray();
modCount++;
int numNew = a.length;
if (numNew == 0)
return false;
Object[] elementData = this.elementData;
final int s = elementCount;
if (numNew > elementData.length - s)
elementData = grow(s + numNew);
int numMoved = s - index;
if (numMoved > 0)
System.arraycopy(elementData, index,
elementData, index + numNew,
numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
elementCount = s + numNew;
return true;
}
equals
Compares the specified Object with this Vector for equality. Returns true if and only if the specified Object is also a List, both Lists have the same size, and all corresponding pairs of elements in the two Lists are equal. (Two elements e1 and e2 are equal if Objects.equals(e1, e2).) In other words, two Lists are defined to be equal if they contain the same elements in the same order.
@param o the Object to be compared for equality with this Vector
@return true if the specified Object is equal to this Vector
public synchronized boolean equals(Object o) {
return super.equals(o);
}
hashCode
Returns the hash code value for this Vector.
public synchronized int hashCode() {
return super.hashCode();
}
toString
Returns a string representation of this Vector, containing the String representation of each element.
public synchronized String toString() {
return super.toString();
}
subList
Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned List is empty.) The returned List is backed by this List, so changes in the returned List are reflected in this List, and vice-versa. The returned List supports all of the optional List operations supported by this List.
This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a List can be used as a range operation by operating on a subList view instead of a whole List. For example, the following idiom removes a range of elements from a List: list.subList(from, to).clear(); Similar idioms may be constructed for indexOf and lastIndexOf, and all of the algorithms in the Collections class can be applied to a subList.
The semantics of the List returned by this method become undefined if the backing list (i.e., this List) is structurally modified in any way other than via the returned List. (Structural modifications are those that change the size of the List, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)
@param fromIndex low endpoint (inclusive) of the subList
@param toIndex high endpoint (exclusive) of the subList
@return a view of the specified range within this List
@throws IndexOutOfBoundsException if an endpoint index value is out of range
(fromIndex < 0 || toIndex > size)
@throws IllegalArgumentException if the endpoint indices are out of order
(fromIndex > toIndex)
public synchronized List<E> subList(int fromIndex, int toIndex) {
return Collections.synchronizedList(super.subList(fromIndex, toIndex),
this);
}
removeRange
Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive. Shifts any succeeding elements to the left (reduces their index). This call shortens the list by (toIndex - fromIndex) elements. (If toIndex==fromIndex, this operation has no effect.)
protected synchronized void removeRange(int fromIndex, int toIndex) {
modCount++;
shiftTailOverGap(elementData, fromIndex, toIndex);
}
shiftTailOverGap
private void shiftTailOverGap(Object[] es, int lo, int hi) {
System.arraycopy(es, hi, es, lo, elementCount - hi);
for (int to = elementCount, i = (elementCount -= hi - lo); i < to; i++)
es[i] = null;
}
readObject
Loads a Vector instance from a stream (that is, deserializes it). This method performs checks to ensure the consistency of the fields.
@param in the stream
@throws java.io.IOException if an I/O error occurs
@throws ClassNotFoundException if the stream contains data
of a non-existing class
@java.io.Serial
private void readObject(ObjectInputStream in) {
ObjectInputStream.GetField gfields = in.readFields();
int count = gfields.get("elementCount", 0);
Object[] data = (Object[])gfields.get("elementData", null);
if (data == null && !gfields.defaulted("elementData") && count > 0) {
// If elementData is null due to 8276665 throwing this exception will not
// overwrite the original ClassNotFoundException exception.
// That exception has been recorded and will be thrown from OIS.readObject.
throw new ClassNotFoundException("elementData is null");
}
if (count < 0 || data == null || count > data.length) {
throw new StreamCorruptedException("Inconsistent vector internals");
}
elementCount = count;
elementData = data.clone();
}
writeObject
Saves the state of the Vector instance to a stream (that is, serializes it). This method performs synchronization to ensure the consistency of the serialized data.
@param s the stream
@throws java.io.IOException if an I/O error occurs
@java.io.Serial
private void writeObject(java.io.ObjectOutputStream s) {
final java.io.ObjectOutputStream.PutField fields = s.putFields();
final Object[] data;
synchronized (this) {
fields.put("capacityIncrement", capacityIncrement);
fields.put("elementCount", elementCount);
data = elementData.clone();
}
fields.put("elementData", data);
s.writeFields();
}
listIterator
Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. The specified index indicates the first element that would be returned by an initial call to next. An initial call to previous would return the element with the specified index minus one.
The returned list iterator is fail-fast.
@throws IndexOutOfBoundsException {@inheritDoc}
public synchronized ListIterator<E> listIterator(int index) {
if (index < 0 || index > elementCount)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
listIterator
Returns a list iterator over the elements in this list (in proper sequence).
The returned list iterator is fail-fast.
@see #listIterator(int)
public synchronized ListIterator<E> listIterator() {
return new ListItr(0);
}
iterator
Returns an iterator over the elements in this list in proper sequence.
The returned iterator is fail-fast.
@return an iterator over the elements in this list in proper sequence
public synchronized Iterator<E> iterator() {
return new Itr();
}
forEach
@throws NullPointerException {@inheritDoc}
@Override
public synchronized void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
final Object[] es = elementData;
final int size = elementCount;
for (int i = 0; modCount == expectedModCount && i < size; i++)
action.accept(elementAt(es, i));
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
replaceAll
@throws NullPointerException {@inheritDoc}
@Override
public synchronized void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final int expectedModCount = modCount;
final Object[] es = elementData;
final int size = elementCount;
for (int i = 0; modCount == expectedModCount && i < size; i++)
es[i] = operator.apply(elementAt(es, i));
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
// TODO(8203662): remove increment of modCount from ...
modCount++;
}
sort
@SuppressWarnings("unchecked")
@Override
public synchronized void sort(Comparator<? super E> c) {
final int expectedModCount = modCount;
Arrays.sort((E[]) elementData, 0, elementCount, c);
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
modCount++;
}
spliterator
Creates a late-binding and fail-fast Spliterator over the elements in this list.
The Spliterator reports SIZED, SUBSIZED, and ORDERED. Overriding implementations should document the reporting of additional characteristic values.
@return a Spliterator over the elements in this list
@since 1.8
@Override
public Spliterator<E> spliterator() {
return new VectorSpliterator(null, 0, -1, 0);
}
checkInvariants
void checkInvariants() {
// assert elementCount >= 0;
// assert elementCount == elementData.length || elementData[elementCount] == null;
}
Itr 类
An optimized version of AbstractList.Itr
属性
cursor
int cursor; // index of next element to return
lastRet
int lastRet = -1; // index of last element returned; -1 if no such
expectedModCount
int expectedModCount = modCount;
方法
hasNext
public boolean hasNext() {
// Racy but within spec, since modifications are checked
// within or after synchronization in next/previous
return cursor != elementCount;
}
next
public E next() {
synchronized (Vector.this) {
checkForComodification();
int i = cursor;
if (i >= elementCount)
throw new NoSuchElementException();
cursor = i + 1;
return elementData(lastRet = i);
}
}
remove
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
synchronized (Vector.this) {
checkForComodification();
Vector.this.remove(lastRet);
expectedModCount = modCount;
}
cursor = lastRet;
lastRet = -1;
}
forEachRemaining
@Override
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
synchronized (Vector.this) {
final int size = elementCount;
int i = cursor;
if (i >= size) {
return;
}
final Object[] es = elementData;
if (i >= es.length)
throw new ConcurrentModificationException();
while (i < size && modCount == expectedModCount)
action.accept(elementAt(es, i++));
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
}
checkForComodification
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
ListItr 类
An optimized version of AbstractList.ListItr
方法
ListItr
ListItr(int index) {
super();
cursor = index;
}
hasPrevious
public boolean hasPrevious() {
return cursor != 0;
}
nextIndex
public int nextIndex() {
return cursor;
}
previousIndex
public int previousIndex() {
return cursor - 1;
}
previous
public E previous() {
synchronized (Vector.this) {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
cursor = i;
return elementData(lastRet = i);
}
}
set
public void set(E e) {
if (lastRet == -1)
throw new IllegalStateException();
synchronized (Vector.this) {
checkForComodification();
Vector.this.set(lastRet, e);
}
}
add
public void add(E e) {
int i = cursor;
synchronized (Vector.this) {
checkForComodification();
Vector.this.add(i, e);
expectedModCount = modCount;
}
cursor = i + 1;
lastRet = -1;
}
VectorSpliterator 类
属性
array
private Object[] array;
index
private int index; // current index, modified on advance/split
fence
private int fence; // -1 until used; then one past last index
expectedModCount
private int expectedModCount; // initialized when fence set
方法
VectorSpliterator
VectorSpliterator(Object[] array, int origin, int fence,
int expectedModCount) {
this.array = array;
this.index = origin;
this.fence = fence;
this.expectedModCount = expectedModCount;
}
getFence
private int getFence() { // initialize on first use
int hi;
if ((hi = fence) < 0) {
synchronized (Vector.this) {
array = elementData;
expectedModCount = modCount;
hi = fence = elementCount;
}
}
return hi;
}
trySplit
public Spliterator<E> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid) ? null :
new VectorSpliterator(array, lo, index = mid, expectedModCount);
}
tryAdvance
@SuppressWarnings("unchecked")
public boolean tryAdvance(Consumer<? super E> action) {
Objects.requireNonNull(action);
int i;
if (getFence() > (i = index)) {
index = i + 1;
action.accept((E)array[i]);
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
return false;
}
forEachRemaining
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int hi = getFence();
final Object[] a = array;
int i;
for (i = index, index = hi; i < hi; i++)
action.accept((E) a[i]);
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
estimateSize
public long estimateSize() {
return getFence() - index;
}
characteristics
public int characteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
}
总结
Vector 类是一个古老版本的数组,是一个线程安全的数组,在方法上加上了同步关键字。同时,由于 Vector 出在 1.0 版本,没有集合框架,因此内部设计、方法名、属性名都与集合框架有些许差别,但是不用担心,Vector 后续实现了 List 接口,也就意味着你可以像用 ArrayList 一样去使用他。但是由于是同步的,性能肯定不如 ArrayList。