肯德基培根芝士蛋堡:Java中Vector的用法

来源:百度文库 编辑:九乡新闻网 时间:2024/04/30 03:42:33
ArrayList会比Vector快,他是非同步的,如果设计涉及到多线程,还是用Vector比较好一些
Vector 类提供了实现可增长数组的功能,随着更多元素加入其中,数组变的更大。在删除一些元素之后,数组变小。
Vector 有三个构造函数,
public Vector(int initialCapacity,int capacityIncrement)
public Vector(int initialCapacity)
public Vector()
Vector 运行时创建一个初始的存储容量initialCapacity,存储容量是以capacityIncrement变量定义的增量增长。初始的存储容量和capacityIncrement 可以在Vector的构造函数中定义。第二个构造函数只创建初始存储容量。第三个构造函数既不指定初始的存储容量也不指定capacityIncrement。
  Vector 类提供的访问方法支持类似数组运算和与Vector 大小相关的运算。类似数组的运算允许向量中增加,删除和插入元素。它们也允许测试矢量的内容和检索指定的元素,与大小相关的运算允许判定字节大小和矢量中元素不数目。
  现针对经常用到的对向量增,删,插功能举例描述:
addElement(Object obj)  
把组件加到向量尾部,同时大小加1,向量容量比以前大1
 
insertElementAt(Object obj, int index)  
把组件加到所定索引处,此后的内容向后移动1 个单位
 
setElementAt(Object obj, int index)
把组件加到所定索引处,此处的内容被代替。

removeElement(Object obj) 把向量中含有本组件内容移走。
removeAllElements() 把向量中所有组件移走,向量大小为0。
例如:
import java.lang.System;
import java.util.Vector;
import java.util.Enumeration;

public class VectorTest{
public static void main(String args[])
{
     Vector v=new Vector();
     v.addElement("one");
     System.out.println(v);
     v.addElement("two");
     System.out.println(v);
     v.addElement("three");
     System.out.println(v);
     v.insertElementAt("zero",0);
     System.out.println(v);;
     v.insertElementAt("oop",3);
     System.out.println(v);
     v.setElementAt("three",3);
     System.out.println(v);
     v.setElementAt("four",4);
     System.out.println(v);
     v.removeAllElements();
     System.out.println(v);
}
}

Vector中的变化情况:

[one]
[one, two]
[one, two, three]
[zero, one, two, three]
[zero, one, two, oop, three]
[zero, one, two, three, three]
[zero, one, two, three, four]
[]