Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1187086
  • 博文数量: 233
  • 博客积分: 6270
  • 博客等级: 准将
  • 技术积分: 1798
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-26 08:32
文章分类

全部博文(233)

文章存档

2011年(31)

2010年(202)

我的朋友

分类: Java

2010-11-24 11:13:08

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

  1. keys() - returns an Enumeration of the keys of this Hashtable
  2. keySet() - returns a Set of the keys
  3. entrySet() - returns a Set of the mappings
  4. 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<String, String> ht = new Hashtable<String, String>();

    for (int i = 0; i < 10000; i++) { 
        ht.put("Key=" + i, "Val=" + i); 
    } 

    // 1. Enumeration 
    long start = System.currentTimeMillis(); 
    Enumeration<String> 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<String> 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<String> 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<Entry<String, String>> 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哦。

阅读(791) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~