作者:NOVEMBER RAIN
日期:2001-1-11 8:41:19
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.Emumeration;
public class Avector{
public static void main(String args[])
{
0. Vector v=new Vector();
1. v.addElement("one");
2. addElement("two");
3. v.addElement("three");
4. v.insertElementAt("zero",0);
5. v.insertElementAt("oop",3);
6. v.setElementAt("three",3);
7. v.setElementAt("four",4);
8. v.removeAllElements();
}
}
Vector中的變化情況:
1. one 2. one 3. one 4. zero 5.zero 6. zero 7. zero
8.
two two one one one one
three two two two two
three oop three three
three three four
另外,Vector 在參數傳遞中發揮著舉足輕重的作用。
在Applet 中有一塊畫布(Canvas) 和一個(Panel), 而Panel 中放著使用者要輸入的資訊,根據這些資訊把參數傳遞到canvas 中,這時在Java 中用一個介面(Interface), 而在介面中需用一個Vector 去傳遞這些參數。另外,在一個類向另一個類參數傳遞就可以用這種方法。
例如:
import java.util.Vector
interface codeselect{
Vector codeselect=new Vector();
}
顯示數學資訊
Vector(0)存入學生編號
Vector(1)存入學科
在Panel 中當使用者在TextField 和Choice 中選擇自己所要求的內容,程式中
通過事件響應把值傳到向量Vector 中。
假若在Panel 類中:
public void codepanel extends Panel{
public void init()
{
**.
TextField s=new TextField();
Choice c=new Choice();
c. addItem("語文");
c.addItem("數學");
c.addItem("政治");
add(s);
add (c);
**
}
public boolean handleEvent(Event event){
if(event.id==Event.ACTION_EVENT){
if(event.target.instanceof Textfield)
{
coderesult.setElementAt(s.getText(),0);
}
else if(event.target intanceof Choice)
{
coderesult.setElementAt(new Integer(c.getSelectedIndex()),1);
}
}
}
}
這時,向量中已經存入學生編號和學科索引號(0 為語文,1 為數學,2 為政治)。
而在Canvas 中得到此值,
public class codecanvas extends Canvas{
public void code{
}
public void paint{
String str;
int t;
str=(String)coderesult.elementAt(0);
t=(new Integer(codeselect.elementAt(1).toString())).intValue();
if(t==0)
{
顯示語文資訊
}
else if(t==1)
{
顯示數學資訊
}
else if(t==2)
{
顯示政治資訊
}
}
}