谨慎使用keySet:对于HashMap的2种遍历方式比较
HashMap存储的是键值对,所以一般情况下其遍历同List及Set应该有所不同.
但java巧妙的将HashMap的键值对作为一个整体对象(java.util.Map.Entry)进行处理,这优化了HashMap的遍历处理,使其遍历同List、Set并无差异.
第一种:
Java代码
- Map map = new HashMap();
- Iterator iter = map.entrySet().iterator();
- while (iter.hasNext()) {
- java.util.Map.Entry entry = (Map.Entry) iter.next();
- Object key = entry.getKey();
- Object val = entry.getValue();
- }
第二种:
Java代码
- Map map = new HashMap();
- Iterator iter = map.keySet().iterator();
- while (iter.hasNext()) {
- Object key = iter.next();
- Object val = map.get(key);
- }
例如:
HashMap的遍历有两种常用的方法,那就是使用keyset及entryset来进行遍历,但两者的遍历速度是有差别的,下面请看实例:
Java代码
- public class HashMapTest {
- public static void main(String[] args) ...{
- HashMap hashmap = new HashMap();
- for (int i = 0; i < 1000; i ) ...{
- hashmap.put("" i, "that's all");
- }
- long num = Calendar.getInstance().getTimeInMillis();
- Iterator iterator = hashmap.keySet().iterator();
- while (iterator.hasNext()) ...{
- System.out.print(hashmap.get(iterator.next()));
- }
- System.out.println();
- System.out.println(Calendar.getInstance().getTimeInMillis() - num);
- listHashMap();
- }
- public static void listHashMap() ...{
- java.util.HashMap hashmap = new java.util.HashMap();
- for (int i = 0; i < 1000; i ) ...{
- hashmap.put("" i, "that's all");
- }
- long num = Calendar.getInstance().getTimeInMillis();
- java.util.Iterator it = hashmap.entrySet().iterator();
- while (it.hasNext()) ...{
- java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
- // entry.getKey() 返回与此项对应的键
- // entry.getValue() 返回与此项对应的值
- System.out.print(entry.getValue());
- }
- System.out.println();
- System.out.println(Calendar.getInstance().getTimeInMillis() - num);
- }
- }
看JDK源码,对比两种访问方式:
首先看KeySet访问方式:
Java代码
- public Set<K> keySet() {
- if (keySet == null) {
- keySet = new AbstractSet<K>() {
- public Iterator<K> iterator() {
- return new Iterator<K>() {
- private Iterator<Entry<K,V>> i = entrySet().iterator();
- public boolean hasNext() {
- return i.hasNext();
- }
- public K next() {
- return i.next().getKey();
- }
- public void remove() {
- i.remove();
- }
- };
- }
- public int size() {
- return AbstractMap.this.size();
- }
- public boolean contains(Object k) {
- return AbstractMap.this.containsKey(k);
- }
- };
- }
- return keySet;
- }
结论:
通过上边的测试我们可以看出,采用entrySet方式遍历效率要优于keySet,因此在开发中要使用entrySet,尽量避免少使用keySet。