EntrySetとkeySetの違い

1795 ワード

ネット上のいくつかの文章を見て、keySetはentrySetより遅いと言っています.私がテストしたところ、両者の違いは大きくありません.
しかもkeySetの方が簡単

import java.util.Calendar;
import java.util.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

/**
 *  keySet() entrySet()  keySet(): get() key
 * entrySet(): e.getKey(),e.getValue() key value。 Entry 
 *  keySet() entrySet() 。 entrySet() 
 * 
 * @author YL
 * @date 2009.6.10
 */
public class Test {
	public static void main(String[] args) {
		Map<String, String> kmap = new TreeMap<String, String>();
		Map<String, String> emap = new TreeMap<String, String>();
		int num = 20000;
		//  
		for (int i = 0; i < num; i++) {
			kmap.put("" + i, "YL");
		}
		for (int i = 0; i < num; i++) {
			emap.put("" + i, "ZT");
		}

		long stimes = System.currentTimeMillis();

		Iterator<String> ktor = kmap.keySet().iterator();
		while (ktor.hasNext()) {
			String k = ktor.next();
			String v = kmap.get(k);
			System.out.println(k + v);
		}

		long stimes1 = System.currentTimeMillis();

		Iterator<Entry<String, String>> itor = emap.entrySet().iterator();
		while (itor.hasNext()) {
			Entry<String, String> e = itor.next();
			String k = e.getKey();
			String v = e.getValue();
			System.out.println(k + v);
		}

		long stimes2 = System.currentTimeMillis();
		System.out.println("keySet: " + (stimes1 - stimes));
		System.out.println("entrySet: " + (stimes2 - stimes1));
	}
}