在Java2之前,Java是没有完整的集合框架的。当时只有一些简单的可以自扩展的容器类,比如Vector,Stack,Hashtable等。
java.util.Vector中包含的元素可以通过一个整型的索引值取得,它的大小可以在添加或移除元素时自动增加或缩小。Vector的操作很简单,通过addElement()加入一个对象,用elementAt()取出它,还可以查询当前所保存的对象的个数size();
用nextElement()获得下一个元素。Enumeration的用意在于使你能完全不用理会你要遍历的容器的基础结构,只关注你的遍历方法,
这也就使得遍历方法的重用成为可能。由于这种思想的强大功能,所以在Java2中被保留下来,不过具体实现,方法名和内部算法都改变了,这就是Java2中的Iterator以及ListIterator类。然而Enumeration的功能却十分有限,比如只能朝一个方向进行,只能读取而不能更改等。
在 Vector文档中可以看到它的很多函数都加了synchronized,从中可知道它的线程安全是通过Vector对象锁来完成。
即每个线程调用这些函数必须获得Vector对象锁,才能继续函数的执行,否则该线程只有等待直到得到该锁。
当然效率就很低
addElement是java1.2前的,是历史遗留。add是Java1.2新加的。remove方法同理。
构造方法
| Public Constructors | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
Vector()
Constructs a new vector using the default capacity.
| |||||||||||
|
Vector(int capacity)
Constructs a new vector using the specified capacity.
| |||||||||||
|
Vector(int capacity, int capacityIncrement)
Constructs a new vector using the specified capacity and capacity increment.
| |||||||||||
|
Vector(
Collection<? extends E> collection)
Constructs a new instance of
Vector containing the elements in
collection.
| |||||||||||
Vector<Integer> v=new Vector();
v.add(new Integer(1));
v.add(new Integer(2));
Enumeration<Integer> e=v.elements();
while (e.hasMoreElements())
{
System.out.println(e.nextElement());
}
v.add("1");
v.add("2");
v.add("3");
while (!v.isEmpty())
System.out.println(v.remove(0));
本文深入探讨了Java集合框架中的Vector类,包括其基本操作、特性、注意事项以及与ArrayList的区别,特别强调了同步性、数据增长策略和元素允许为null的特点。
287

被折叠的 条评论
为什么被折叠?



