Vector类与Enumeration接口

Vector类用于保存一组对象,由于java不支持动态数组,Vector可以用于实现跟动态数组差不多的功能。如果要将一组对象存放在某种数据结构中,但是不能确定对象的个数时,Vector是一个不错的选择。

例:将键盘上输入的一个数字序列的每位数字存储在vector对象中,然后在屏幕上打印出各位数字相加的结果。

import java.util.*; //Vector类和Enumeration接口都在这个包中

public class TestVector

{

public static void main(String[] args)

{

Vector v=new Vector();

int b=0;

int num=0;

System.out.println("Please enter number:");

while(true)

{

try

{

b=System.in.read(); //从键盘读入一个字节内容

}

catch(Exception e)

{

e.printStackTrace();

}

if(b==' '||b==' ') //如果是回车或换行的话,则退出while循环,即一串数据输入完成

{

break;

}

else

{

num=b-'0';

/*由于输入的是字符数字,它的数值是它的ascii码,例如‘0’=32;‘1’=33,

所以要想让输入的‘1’在计算机里为1,必须减去32,即‘0’*/

v.addElement(new Integer(num)); //将数字存入vector

}

}

int sum=0;

Enumeration e=v.elements();

//取出Vector中的所有元素,必须使用elements()方法,它返回一个Enumeration接口。

while(e.hasMoreElements())//如果当前指示器还指向一个对象,即还有数据

{

Integer intobj=(Integer)e.nextElement();

//取出当前指示器所指的对象,并将指示器指向下一个对象。

sum+=intobj.intValue(); //将Integer对象中所包装的整数取出来,并且加到sum中。

}

System.out.println(sum);//打印出这个和

}

}

Enumeration的nextelement()方法返回的是指示器指示的对象,然后将指示器指向下一个对象。

由于vector可以存储各种类型的对象,所以编译器无法知道存储的是什么类型的对象,所以即使我们知道里面存储的是什么类型的,也要显示的说明它是什么类型的,如本例中的(Integer)e.nextElement();

Enumeration接口实现了一种机制,通过这种机制,我们就可以只用hasMoreElements()方法以及nextElement()方法就可以实现所有对象的访问。

 

原文地址:https://www.cnblogs.com/borter/p/9434173.html