关于集合类
集合类用于存储一组对象,其中的每个对象称之为元素,经常会用到的有Vector、Enumeration、ArrayList、Collection、Iterator、Set、List等集合类和接口。
1、Vector类和Enumeration接口
(1)Vector类
Vector类时java语言提供的一种高级数据结构,可用于保存一系列的对象,由于java不支持动态数组,Vector类提供了一种与动态数组相近的功能。如果要将若干对象保存在原一种数据结构中,但不能预先知道对象的数目时,Vector类是一个不错的选择。
(2)编程举例:
将键盘上的一个数字序列号的每位数字存储在Vector对象中,然后在屏幕上打印出每位数字想家的结果,例如,输入32,打印出5;输入1234,打印出10
import java.util.Enumeration;
import java.util.Vector;
public class TestVector1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Vector v = new Vector();
System.out.println("please enter number:");
int b = 0;
while(true)
{
try
{
b = System.in.read();
}
catch(Exception e)
{
e.printStackTrace();
}
if(b=='\r' || b=='\n')
break;
else
{
int num = b - '0';
v.addElement(new Integer(num));
}
}
int sum = 0;
Enumeration e = v.elements();//枚举
while(e.hasMoreElements())//测试此枚举是否包含更多的元素。
{
Integer intObj =(Integer)e.nextElement();
sum +=intObj.intValue();
}
System.out.println(sum);
}
}