1. Introduction
1.导言
The Vector class is a thread-safe implementation of a growable array of objects. It implements the java.util.List interface and is a member of the Java Collections Framework. While it’s similar to ArrayList, these classes have significant differences in their implementations.
Vector 类是可增长对象数组的线程安全实现。它实现了 java.util.List 接口,是 Java 集合框架的成员。虽然它与 ArrayList 相似,但这些类在实现上有很大的不同。
In this tutorial, we’ll explore the Vector class and some of its most common operations and methods.
在本教程中,我们将探讨 Vector 类及其一些最常用的操作和方法。
2. How Does Vector Work?
2.Vector 如何工作?
The Vector class is designed to function as a dynamic array that can expand or shrink according to the application’s needs. Thus, we can access the objects of the Vector using the indices. Additionally, it maintains the insertion order and stores duplicate elements.
Vector 类被设计为动态数组,可根据应用程序的需要扩展或缩小。因此,我们可以使用索引访问 Vector 的对象。此外,它还能保持插入顺序并存储重复元素。
Every Vector aims to enhance its storage handling by keeping track of both the capacity and the capacityIncrement. The capacity is nothing but the size of the Vector. The size of the Vector increases as we add elements to it. Therefore, the capacity remains consistently equal to or greater than the Vector‘s size.
每个 Vector 都希望通过跟踪容量和 capacityIncrement 来增强其存储处理能力。容量只是 Vector 的大小。当我们向 Vector 中添加元素时,Vector 的大小也会增加。因此,容量始终等于或大于 Vector 的大小。
Every time the length of a Vector reaches its capacity, the new length is calculated:
每当 Vector 的长度达到其容量时,就会计算出新的长度:
newLength = capacityIncrement == 0 ? currentSize * 2 : currentSize + capacityIncrement
Similar to ArrayList, the iterators of the Vector class are also fail-fast. It throws a ConcurrentModificationException if we try to modify the Vector while iterating over it. However, we can access the iterator’s add() or remove() methods to structurally modify the Vector.
与 ArrayList 类似,Vector 类的迭代器也是快速失败的。如果我们在迭代 Vector 时试图修改该迭代器,它将抛出 ConcurrentModificationException 异常。但是,我们可以访问迭代器的 add() 或 remove() 方法来对 Vector 进行结构修改。
3. How to Use Vector
3.如何使用 Vector
Let’s see how to create a Vector and perform various operations on it.
让我们看看如何创建 Vector 并对其执行各种操作。
3.1. Creating a Vector
3.1.创建 向量</em
We can create Vector instances using the constructor. There are four different types of Vector constructors.
我们可以使用构造函数创建 Vector 实例。有四种不同类型的 Vector 构造函数。
The first is the default constructor, which creates an empty Vector with the initial capacity of 10 and a standard capacityIncrement of 0:
第一个是 默认构造函数,它创建了一个空 Vector ,初始容量为 10,标准 capacityIncrement 为 0:
Vector<T> vector = new Vector<T>();
We can create an empty Vector by specifying its initial size (capacity). In this case, its capacityIncrement is also set to 0:
我们可以通过指定初始大小(容量)来创建一个空的 Vector 。在这种情况下,其 capacityIncrement 也将设置为 0:
Vector<T> vector = new Vector<T>(int size);
There’s another constructor using which we can specify the initial capacity and capacityIncrement to create an empty Vector:
我们还可以使用另一个构造函数来指定初始容量和 capacityIncrement 以创建一个空的 Vector :
Vector<T> vector = new Vector<T>(int size, int capacityIncrement);
Finally, we can construct a Vector by passing another Collection to the constructor. The resultant Vector contains all the elements of the specified Collection:
最后,我们可以通过向构造函数传递另一个 Collection 来构造一个 Vector 。生成的 Vector 包含指定 Collection 中的所有元素:
Vector<T> vector = new Vector(Collection<T> collection);
3.2. Adding Elements to Vector
3.2.为 Vector 添加元素
Let’s create a method that returns a Vector. We’ll use this method for future operations:
让我们创建一个返回 Vector 的方法。我们将在以后的操作中使用该方法:
Vector<String> getVector() {
Vector<String> vector = new Vector<String>();
vector.add("Today");
vector.add("is");
vector.add("a");
vector.add("great");
vector.add("day!");
return vector;
}
Here, we’ve created an empty Vector of Strings with a default constructor and added a few Strings.
在这里,我们使用默认构造函数创建了一个由 String 组成的空 Vector 并添加了几个 String 。
Based on the needs, we can add elements at the end or a specific index to a Vector. For this, we can use the add() method which is overloaded to satisfy various needs.
根据需要,我们可以在 Vector 的末尾或特定索引中添加元素。为此,我们可以使用重载的 add() 方法来满足各种需求。
Now, let’s add an element at a specific index to vector:
现在,让我们在 vector 中添加一个特定索引的元素:
vector.add(2, "not"); // add "not" at index 2
assertEquals("not", vector.get(2)); // vector = [Today, is, not, a, great, day!]
Here, we use the add(int index, E element) method of the Vector class to add the String “not” at index 2. We should note that it shifts all the elements after the specified index to the right by one position. Thus, the String “not” is added between the Strings “is” and “a“.
在此,我们使用 Vector 类的 add(int index, E element) 方法在索引 2 处添加 String“not” 。我们应该注意到,它将指定索引后的所有元素向右移动了一个位置。因此,String “not” 被添加到 Strings “is” 和 “a” 之间。
Similarly, we can add all the elements of a Collection to a Vector using the method addAll(Collection c). Using this method, we can append all the elements of a collection to the end of the Vector in the same order as that of the Collection:
同样,我们可以使用方法 addAll(Collection c) 将 Collection 中的所有元素添加到 Vector 中。使用该方法,我们可以将集合的所有元素按照与 Collection 相同的顺序追加到 Vector 的末尾:
ArrayList<String> words = new ArrayList<>(Arrays.asList("Baeldung", "is", "cool!"));
vector.addAll(words);
assertEquals(9, vector.size());
assertEquals("cool!", vector.get(8));
After the execution of the above code, if we print vector, we’ll get the following:
执行上述代码后,如果打印 vector ,我们将得到以下结果:
[Today, is, not, a, great, day!, Baeldung, is, cool!]
3.3. Updating Elements
3.3.更新元素
We can use the set() method to update the elements of a Vector. The set() method replaces the element at the specified index with the new element while returning the replaced element. Consequently, it accepts two arguments – the index of the element to be replaced, and the new element:
我们可以使用 set() 方法更新 Vector 中的元素。set()方法用新元素替换指定索引处的元素,同时返回被替换的元素。因此,它接受两个参数–要替换元素的索引和新元素:
Vector<String> vector = getVector();
assertEquals(5, vector.size());
vector.set(3, "good");
assertEquals("good", vector.get(3));
3.4. Removing Elements
3.4.删除元素
We can use the remove() method to remove an element from a Vector. It has been overloaded according to various needs. As a result, we can remove a specific element or an element at a specific index, or all the elements of a Vector. Let’s see a few examples.
我们可以使用 remove() 方法从 Vector 中移除一个元素。该方法已根据各种需要进行了重载。因此,我们可以删除特定元素、特定索引处的元素或 Vector 中的所有元素。让我们来看几个例子。
If we pass an object to the remove() method, the first occurrence of it is deleted:
如果我们将一个对象传递给 remove() 方法,那么它的第一次出现就会被删除:
Vector<String> vector = getVector();
assertEquals(5, vector.size());
vector.remove("a");
assertEquals(4, vector.size()); // vector = [Today, is, great, day!]
Similarly, if we now pass 2 to the remove() method above, it deletes the element, great, at index 2:
同样,如果我们现在将 2 传递给上述 remove() 方法,它将删除索引 2 处的元素 great :
vector.remove(2);
assertEquals("day!", vector.get(2));
We should note that all the elements to the right of the deleted element shift to their left by one position. Moreover, the remove() method throws an ArrayIndexOutOfBoundsException if we provide the index beyond the range of the Vector, i.e., index < 0 or index >= size().
我们应该注意到,被删除元素右侧的所有元素都会向左移动一个位置。此外,如果我们提供的索引超出了 Vector 的范围,即 index < 0 或 index >= size(),remove() 方法将抛出 ArrayIndexOutOfBoundsException 异常。
Finally, let’s remove all the elements of vector:
最后,让我们删除 vector 的所有元素:
vector.removeAll();
assertEquals(0, vector.size());
3.5. Getting an Element
3.5.获取元素
We can use the get() method to get an element of the Vector at a particular index:
我们可以使用 get() 方法获取特定索引处的 Vector 元素:
Vector<String> vector = getVector();
String fourthElement = vector.get(3);
assertEquals("great", fourthElement);
The get() method also throws an ArrayIndexOutOfBoundsException if we provide the index beyond the range of the Vector.
如果我们提供的索引超出了 Vector 的范围,get() 方法也会抛出 ArrayIndexOutOfBoundsException 异常。
3.6. Iterating Through a Vector
3.6.遍历 向量</em
We can iterate through a Vector in multiple ways. However, one of the most common ways is the for-each loop:
我们可以通过多种方式遍历一个 Vector 。但是,最常用的方法之一是 for-each 循环:
Vector<String> vector = getVector();
for(String string : vector) {
System.out.println(string);
}
We can also use the forEach() method to iterate through a Vector, especially when we want to perform a certain action on each element:
我们还可以使用forEach() 方法遍历 Vector ,尤其是当我们想对每个元素执行特定操作时:
Vector<String> vector = getVector();
vector.forEach(System.out::println);
4. When to Use Vector
4.何时使用 向量</em
The first and obvious use of Vector is when we need a growable collection of objects. If we’re unsure about the size of the growing collection, but we know how frequently we’ll add or remove the elements, then we may prefer to use a Vector. In such cases, we can set capacityIncrement according to the situation.
Vector 的第一种明显用途是当我们需要一个可增长的对象集合时。如果我们不确定增长集合的大小,但我们知道添加或删除元素的频率,那么我们可能更倾向于使用 Vector 。在这种情况下,我们可以根据实际情况设置 capacityIncrement 。
However, since Vector is synchronized, it’s preferable to use it in case of multithreaded applications. In the case of single-threaded applications, ArrayList works much faster compared to Vector. Moreover, we can synchronize ArrayList explicitly using Collections.synchronizedList().
不过,由于 Vector 是同步的,因此在多线程应用程序中最好使用它。在单线程应用程序中,ArrayList 的运行速度要比 Vector 快得多。此外,我们还可以使用 Collections.synchronizedList() 显式同步 ArrayList。
5. Conclusion
5.结论
In this article, we had a look at the Vector class in Java. We also explored how to create a Vector instance and how to add, find, or remove elements using different approaches.
在本文中,我们了解了 Java 中的 Vector 类。我们还探讨了如何创建 Vector 实例,以及如何使用不同的方法添加、查找或删除元素。
As always, the source code for the article is available over on GitHub.
一如既往,本文的源代码可在 GitHub 上获取。