Java中的Vector

来源:互联网 发布:网络财经编辑招聘 编辑:程序博客网 时间:2024/06/05 04:38
Vector(矢量)
addElement() 置入对象
elementAt() 取得对象

size() 返回添加的对象数


class Cat(){private int number = -1;public Cat(int i){number = i;}public void print(){System.out.println("Cat" + number);}}public class Test(){public static void main(String [] args){Vector cats = new Vector();for(int i = 0; i < 3; i++){cats.addElement(new Cat(i);}for(int i = 0; i < cats.size(); i++){(Cat)cats.elementAt(i).print();}}}
可以不使用for循环,使用迭代器(Iterator)来输出Vector中的对象。


Enumeration e = cats.elememts();while(e.hasMoreElements()){((Cat)e.nextElement()).print();}
我们使用了 Enumeration(枚举) 这个有限制的迭代器。
1.使用 elememts() 方法要求集合为我们提供一个 Enumeration 对象;
2.用 nextElement() 方法返回下一个对象,首次调用该方法返回序列中的第一个对象;
3.用 hasMoreElements() 检查序列中是否还有更多的对象。