现在的位置: 首页 > 综合 > 正文

Vector简介

2013年10月09日 ⁄ 综合 ⁄ 共 1623字 ⁄ 字号 评论关闭

在Java2之前,Java是没有完整的集合框架的。当时只有一些简单的可以自扩展的容器类,比如Vector,Stack,Hashtable等。

java.util.Vector中包含的元素可以通过一个整型的索引值取得,它的大小可以在添加或移除元素时自动增加或缩小。Vector的操作很简单,通过addElement()加入一个对象,用elementAt()取出它,还可以查询当前所保存的对象的个数size();

  另外还有一个
Enumeration类提供了连续操作Vector中元素的方法,这可以通过Vector中的elements()方法来获取一个Enumeration类的对象,可以用一个While循环来遍历其中的元素。用hasMoreElements()检查其中是否还有更多的元素。

  用nextElement()获得下一个元素。
Enumeration的用意在于使你能完全不用理会你要遍历的容器的基础结构,只关注你的遍历方法,

  这也就使得遍历方法的重用成为可能。由于这种思想的强大功能,所以在Java2中被保留下来,不过具体实现,方法名和内部算法都改变了,这就是
Java2中的Iterator以及ListIterator类。然而Enumeration的功能却十分有限,比如只能朝一个方向进行,只能读取而不能更改等。

  注意1:同步性:Vector是线程安全的,也就是说是同步的,而ArrayList是线程序不安全的,不是同步的.

  在 Vector文档中可以看到它的很多函数都加了synchronized,从中可知道它的线程安全是通过Vector对象锁来完成。

  即每个线程调用这些函数必须获得Vector对象锁,才能继续函数的执行,否则该线程只有等待直到得到该锁。

  当然效率就很低


  注意2:数据增长:其大小也是动态增长的。当需要增长时,Vector默认增长为原来一培,而ArrayList却是原来的一半 

  注意3里面的元素可以为null

  注意4asynchronized boolean     add(E object)和 synchronized void     addElement(E object)功能都是一样的。

  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.

例1
  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());

  }

例2
  v.add("1");

  v.add("2");

  v.add("3");

  
while(!v.isEmpty())

   System.out.println(v.remove(0));


抱歉!评论已关闭.