遍历hashtable java_通过Enumeration和Iterator遍历Hashtable的效率分析

今天需要遍历一个Hashtable,查看了一下Hashtable类,发现它提供了如下几个方法可供我们遍历:

keys() - returns an Enumeration of the keys of this Hashtable

keySet() - returns a Set of the keys

entrySet() - returns a Set of the mappings

elements() - returns an Enumeration of the values of this Hashtable

4种方法,那种更好呢,写段代码来比较一下吧:

import java.util.Enumeration;

import java.util.Hashtable;

import java.util.Iterator;

import java.util.Map.Entry;

public class traveseHashTable {

public static void main(String[] args) {

Hashtable ht = new Hashtable();

for (int i = 0; i < 10000; i++) {

ht.put("Key=" + i, "Val=" + i);

}

// 1. Enumeration

long start = System.currentTimeMillis();

Enumeration en = ht.keys();

while (en.hasMoreElements()) {

en.nextElement();

}

long end = System.currentTimeMillis();

System.out.println("Enumeration keys costs " + (end - start)

+ " milliseconds");

// 2. Enumeration

start = System.currentTimeMillis();

Enumeration en2 = ht.elements();

while (en2.hasMoreElements()) {

en2.nextElement();

}

end = System.currentTimeMillis();

System.out.println("Enumeration elements costs " + (end - start) + " milliseconds");

// 3. Iterator

start = System.currentTimeMillis();

Iterator it = ht.keySet().iterator();

while (it.hasNext()) {

it.next();

}

end = System.currentTimeMillis();

System.out.println("Iterator keySet costs " + (end - start) + " milliseconds");

// 4. Iterator

start = System.currentTimeMillis();

Iterator> it2 = ht.entrySet().iterator();

while (it2.hasNext()) {

it2.next();

}

end = System.currentTimeMillis();

System.out.println("Iterator entrySet costs " + (end - start) + " milliseconds");

}

}

这里创建了一个10000个元素的Hashtable来供我们遍历,打印出结果如下:

Enumeration keys costs 6 milliseconds

Enumeration elements costs 5 milliseconds

Iterator keySet costs 10 milliseconds

Iterator entrySet costs 10 milliseconds

我们看到,通过迭代来遍历比枚举要多花尽一倍的时间。所以建议大家通过枚举类来遍历Hashtable哦。

编辑特别推荐:来源:考试大-Java认证

责编:liyan  评论 纠错

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值