慎用“古老”接口Enumeration

来源:互联网 发布:pdf合并拆分的软件 编辑:程序博客网 时间:2024/06/18 05:27

1 Enumeration接口介绍

        Enumeration接口是Iterator迭代器的“古老版本”,从JDK1.0开始,Enumeration接口就已经存在了(Iterator从JDK1.2才出现)。Enumeration 接口比Iterator小,只有两个名字很长的方法: 

  • boolean hasMoreElements( ):如果此迭代器还有剩下的元素则返回true。
  • Object nextElement( ):返回该迭代器的下一个元素,如果还有的话(否则抛出异常)。

2 代码示例

import java.util.*;public class EnumerationTest{public static void main(String[] args){Vector v = new Vector();v.add("电信用户");v.add("联通用户");Hashtable scores = new Hashtable();scores.put("线性代数" , 78);scores.put("大学物理" , 88);Enumeration em = v.elements();while (em.hasMoreElements()){System.out.println(em.nextElement());}Enumeration keyEm = scores.keys();while (keyEm.hasMoreElements()){Object key = keyEm.nextElement();System.out.println(key + "--->"+ scores.get(key));}}}

 

3 运行结果

电信用户
联通用户
大学物理--->88
线性代数--->78

 

4 结果分析

上面的程序使用Enumeration迭代器来遍历Vector和Hashtable集合里的元素,其工作方式和Iterator迭代器的工作方式基本相似。但使用该迭代器时方法名更加冗长,而且Enumeration迭代器支能遍历Vector和Hashtable这种古老的集合,因此不要使用它。除非在很极端的情况下,不得不使用Enumeration,否则都应该选择Iterator迭代器。

0 0
原创粉丝点击