Java 简明教程
Java Vector Class
Introduction
Vector 实现了一个动态数组。它类似于 ArrayList,但有以下两个区别:
-
Vector is synchronized.
-
Vector 包含许多传统方法,这些方法不是集合框架的一部分。
如果你事先不知道数组的大小,或者只需要一个可以在程序生命周期内变大小的数组,Vector 会非常有用。
java.util.Vector 类实现了可增长的对象数组。类似于 Array,它包含可以使用整数索引访问的组件。以下是有关 Vector 的重要事项:
-
Vector 的大小可以根据需要而增长或缩小,以适应添加和删除项目。
-
每个向量都尝试通过维护容量和容量增量来优化存储管理。
-
从 Java 2 平台 v1.2 开始,该类被改装为实现列表接口。
-
与新的集合实现不同,Vector 处于同步状态。
-
此类是 Java 集合框架的成员。
Class declaration
下面是 java.util.Vector 的声明 −
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
此处 <E> 代表一个元素,该元素可以是任何类。例如,如果你正在构建一个整数数组列表,则你可以按照如下方式对其进行初始化 −
ArrayList<Integer> list = new ArrayList<Integer>();
Adding Elements and Iterating a Vector Example
下面的程序说明了 Vector 集合支持的几种方法:
import java.util.*;
public class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " + v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " + (Integer)v.firstElement());
System.out.println("Last element: " + (Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
这会产生以下结果 −