程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Vector在Java編程中的應用

Vector在Java編程中的應用

編輯:關於JAVA

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[]){
   Vector v=new Vector();
   v.addElement("one");
   v.addElement("two");
  v.addElement("three");
  v.insertElementAt("zero",0);
  v.insertElementAt("oop",3);
  v.setElementAt("three",3);
     v.setElementAt("four",4);
   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)
  {
  顯示政治信息
  }
  }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved