Hashtable类中的四种遍历方法对比

本文通过实验比较了四种遍历Hashtable的方法:使用keys()、elements()、keySet()和entrySet(),并分析了每种方法的性能表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

要遍历一个Hashtable,api中提供了如下几个方法可供我们遍历:

  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 HashtableTest {
     public static void main(String[] args) {
           long start = 0;
           long end = 0;
          
          Hashtable<String, String> table = new Hashtable<String, String>();
           for( int i = 0; i < 1000000; i++) {
              table.put( "key:" + i, "value:" + i);
          }
          
           //1、使用keys()
          start = System. currentTimeMillis();
          Enumeration<String> en1 = table.keys();
           while(en1.hasMoreElements()) {
              en1.nextElement();
          }
          end = System. currentTimeMillis();
          System. out.println( "Enumeration keys costs " + (end - start) + " milliseconds" );
          
           //2、使用elements()
          start = System. currentTimeMillis();
          Enumeration<String> en2 = table.elements();
           while(en2.hasMoreElements()) {
              en2.nextElement();
          }
          end = System. currentTimeMillis();
          System. out.println( "Enumeration elements costs " + (end - start) + " milliseconds" );
          
           //3、使用keySet()
          start = System. currentTimeMillis();
          Iterator<String> it1 = table.keySet().iterator();
           while(it1.hasNext()) {
              it1.next();
          }
          end = System. currentTimeMillis();
          System. out.println( "Iterator keySet costs " + (end - start) + " milliseconds" );
          
           //4、使用entrySet()
          start = System. currentTimeMillis();
          Iterator<Entry<String, String>> it2 = table.entrySet().iterator();
           while(it2.hasNext()) {
              it2.next();
          }
          end = System. currentTimeMillis();
          System. out.println( "Iterator entrySet costs " + (end - start) + " milliseconds" );
     }
}

运行结果如下:
Enumeration keys costs 16 milliseconds
Enumeration elements costs 15 milliseconds
Iterator keySet costs 17 milliseconds
Iterator entrySet costs 16 milliseconds

通过运行结果显示,在如今jdk的版本下,两者差距不是很大,不过使用Enumeration去遍历会稍微快一些。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值