对集合类Vector和Enumeration的应用

来源:互联网 发布:游戏数据修改器 编辑:程序博客网 时间:2024/06/03 16:48

这里写图片描述
代码如下:

import java.util.*;public class TestVector {    public static void main(String[] args) {        int b = 0;        Vector v = new Vector();        System.out.println("please enter number:");        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(); // Enumeration接受的都为object类型的数据,所以要强制转换            sum += intObj.intValue();        }        System.out.println(sum);    }}

运行结果:
这里写图片描述

要仔细体会Vector和Enumeration的应用。
说道Vector和Enumeration就想到Collection和Iterator,用Collection和Iterator实现上面例子的代码如下:

import java.util.*;public class TestCollection {    public static void main(String[] args) {        int b = 0;        ArrayList v = new ArrayList();        System.out.println("please enter number:");        while (true) {            try {                b = System.in.read();            } catch (Exception e) {                e.printStackTrace();            }            if (b == '\r' || b == '\n')                break;            else {                int num = b - '0';                v.add(new Integer(num));            }        }        int sum = 0;        Iterator e = v.iterator();        while (e.hasNext()) {            Integer intObj = (Integer) e.next();            sum += intObj.intValue();        }        System.out.println(sum);    }}

运行结果:
这里写图片描述

Vector和Enumeration内部实现了多线程同步,所以在使用多线程时就应该用Vector和Enumeration实现,而Collection和Iterator没有实现多线程同步,所以运行速度较快,但在多线程的应用程序就要自己编写线程的同步。

1 0
原创粉丝点击