对集合类Vector和Enumeration的应用


代码如下:

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没有实现多线程同步,所以运行速度较快,但在多线程的应用程序就要自己编写线程的同步。

你可能感兴趣的:(java,应用)