Java 数据结构 --> Vector 类

来源:互联网 发布:电脑维修书籍推荐 知乎 编辑:程序博客网 时间:2024/06/05 05:36
Vector类实现了一个动态数组。和ArrayList和相似,但是两者是不同的:
    Vector是同步访问的。
    Vector包含了许多传统的方法,这些方法不属于集合框架。

Vector主要用在事先不知道数组的大小,或者只是需要一个可以改变大小的数组的情况。


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();
   }

运行结果:

Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.


Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12


0 0
原创粉丝点击