当前位置: 代码迷 >> 综合 >> Java Vector 类使用,与Arraylist的区别
  详细解决方案

Java Vector 类使用,与Arraylist的区别

热度:45   发布时间:2024-01-26 12:28:44.0
import java.util.*;/*
向量“二者都有一个初始容量大小,采用线性连续存储空间;
当Vector或ArrayList中的元素超过它的初始大小时,Vector会将它的容量翻倍,
而ArrayList只增加50%的大小,这样ArrayList就有利于节约内存空间。
Vector的方法都是同步的,是线程安全的,而ArrayList的方法不是,当只有一个线程操作集合时,最好用ArrayList,
当多线程操作集合时,用Vector,因为它线程是安全的”*/
public class VectorDemo {public static void main(String args[]) {// initial size is 3, increment is 2Vector v = new Vector(3, 2);// 第三种构造方法创建指定大小的向量,并且增量用 incr 指定。增量表示向量每次增加的元素数目。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));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();}
}