相關(guān)軟件 >Vector在Java編程中的應(yīng)用 創(chuàng)建者:webmaster 更新時(shí)間:2005-05-30 22:56 Vector 類提供了實(shí)現(xiàn)可增長數(shù)組的功能,隨著更多元素加入其中,數(shù)組變的更大。在刪除一些元素之后,數(shù)組變小。 Vector 有三個(gè)構(gòu)造函數(shù), public Vector(int initialCapacity,int capacityIncrement) public Vector(int initialCapacity) public Vector() Vector 運(yùn)行時(shí)創(chuàng)建一個(gè)初始的存儲(chǔ)容量initialCapacity,存儲(chǔ)容量是以capacityIncrement 變量定義的增量增長。初始的存儲(chǔ)容量和capacityIncrement 可以在Vector 的構(gòu)造函數(shù)中定義。第二個(gè)構(gòu)造函數(shù)只創(chuàng)建初始存儲(chǔ)容量。第三個(gè)構(gòu)造函數(shù)既不指定初始的存儲(chǔ)容量也不指定capacityIncrement。 Vector 類提供的訪問方法支持類似數(shù)組運(yùn)算和與Vector 大小相關(guān)的運(yùn)算。類似數(shù)組的運(yùn)算允許向量中增加,刪除和插入元素。它們也允許測試矢量的內(nèi)容和檢索指定的元素,與大小相關(guān)的運(yùn)算允許判定字節(jié)大小和矢量中元素不數(shù)目。 現(xiàn)針對經(jīng)常用到的對向量增,刪,插功能舉例描述: addElement(Object obj) 把組件加到向量尾部,同時(shí)大小加1,向量容量比以前大1 insertElementAt(Object obj, int index) 把組件加到所定索引處,此后的內(nèi)容向后移動(dòng)1 個(gè)單位 setElementAt(Object obj, int index) 把組件加到所定索引處,此處的內(nèi)容被代替。 removeElement(Object obj) 把向量中含有本組件內(nèi)容移走。 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 在參數(shù)傳遞中發(fā)揮著舉足輕重的作用。 在Applet 中有一塊畫布(Canvas) 和一個(gè)(Panel), 而Panel 中放著用戶要輸入的信息,根據(jù)這些信息把參數(shù)傳遞到canvas 中,這時(shí)在Java 中用一個(gè)接口(Interface), 而在接口中需用一個(gè)Vector 去傳遞這些參數(shù)。另外,在一個(gè)類向另一個(gè)類參數(shù)傳遞就可以用這種方法。 例如: import java.util.Vector interface codeselect{ Vector codeselect=new Vector(); } 顯示數(shù)學(xué)信息 Vector(0)存入學(xué)生編號 Vector(1)存入學(xué)科 在Panel 中當(dāng)用戶在TextField 和Choice 中選擇自己所要求的內(nèi)容,程序中 通過事件響應(yīng)把值傳到向量Vector 中。 假若在Panel 類中: public void codepanel extends Panel{ public void init() { **. TextField s=new TextField(); Choice c=new Choice(); c. addItem("語文"); c.addItem("數(shù)學(xué)"); 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); } } } } 這時(shí),向量中已經(jīng)存入學(xué)生編號和學(xué)科索引號(0 為語文,1 為數(shù)學(xué),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) { 顯示數(shù)學(xué)信息 } else if(t==2) { 顯示政治信息 } } } 非本人作品,自供自己學(xué)習(xí) 使用 相關(guān)文章 本頁查看次數(shù):