java 遍历 HashMap,两种方式:使用条目集进行迭代和使用枚举进行迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15591319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:10:33  来源:igfitidea点击:

Iterating over a HashMap, two ways: iterating with entry set & iterating with enumeration

javahashmapiteratorkey

提问by MdT

Are HashMaps supposed to be iterated in these two ways or is enumeration considered wrong? I made a simple iterator program with two iterator functions:

HashMaps 应该以这两种方式进行迭代还是枚举被认为是错误的?我用两个迭代器函数做了一个简单的迭代器程序:

import java.util.*;

public class HashMapIterators
{
    public static void main(String[] args)
    {
        HashMap<String, Integer> hMap = new HashMap<String, Integer>();

        hMap.put("abc", 10);
        hMap.put("pqr", 20);
        hMap.put("asd", 30);
        hMap.put("xyz", 40);

        iteratorEnumeration(hMap);
        iteratorEntrySet(hMap);
    }

    public static void iteratorEnumeration(HashMap hMap)
    {
        System.out.println("iteratorEnumeration");

        Iterator it = hMap.keySet().iterator();
        Enumeration em = hMap.elements();               // doesn't work
        Enumeration em = new IteratorEnumeration(it);   // doesn't work

//      while(em.hasMoreElements())
        {
        }
    }

    public static void iteratorEntrySet(HashMap hMap)
    {
        System.out.println("iteratorEntrySet");

        Iterator it = hMap.entrySet().iterator();

        while(it.hasNext())
        {
            Map.Entry me = (Map.Entry)it.next();
            System.out.println("Key: [" + me.getKey() + "], Value: [" + me.getValue() + "]");
        }
    }
}

The iteratorEnumeration function does not work, I guess these methods (like elements()) is applicable on HashTable's only. Correct me if i'm wrong, I don't know when is it appropriate to use what function. So, my main question is - should we iterate over a HashMap by setting a iterator over the entrySet method (please see my iteratorEntrySet function), is this the only right way to do it?

iteratorEnumeration 函数不起作用,我猜这些方法(如元素())仅适用于 HashTable。如果我错了,请纠正我,我不知道什么时候使用什么功能合适。所以,我的主要问题是 - 我们是否应该通过在 entrySet 方法上设置迭代器来迭代 HashMap(请参阅我的 iteratorEntrySet 函数),这是唯一正确的方法吗?

回答by ratchet freak

first of generics, learn 'em &love 'em

首先是泛型,学习它们并热爱它们

second the keySet also has a iterator()method that iterates over all keys (the Enumerationclass is deprecated)

其次,keySet 也有一个iterator()迭代所有键的方法(Enumeration该类已弃用)

I find the entrySetbetter when I also need the value on each key so I can avoid the cost of the search (which depending on the map can go to O(n))

entrySet当我还需要每个键的值时,我发现更好,这样我就可以避免搜索成本(这取决于地图可以转到O(n)

the iteration code comes down to:

迭代代码归结为:

for(Map.Entry<KeyClass,ValueClass> e:hMap){
    KeyClass key = e.getKey();
    ValueClass value = e.getValue();
    //...
}

if I just need the keys I'll use the keySet as to avoid the extra bloat of Map.entry<keyClass,ValueClass>in the for type

如果我只需要密钥,我将使用 keySet 以避免Map.entry<keyClass,ValueClass>for 类型中的额外膨胀

回答by MrLore

The easiest way to do this would be to use the new Enhanced forLoop(Foreach), along with generics like so:

最简单的方法是使用新的增强for循环(Foreach),以及像这样的泛型:

static <K, V> void iterateForEach(Map<K, V> map)
{
    for(Map.Entry<K, V> entry : map.entrySet())
    {
        System.out.println("Key: [" + entry.getKey() + "], Value: [" + entry.getValue() + "]");
    }
}

回答by hvgotcodes

Is the way you interact with the Map? If so, you might be using they wrong data structure.

是你与地图互动的方式吗?如果是这样,您可能使用了错误的数据结构。

Any way, the problem with your iteratorEnumeration method is once you get the key iterator, you should iterate over it, getting the value from the map each time. You dont need to call hMap.elements();

无论如何,您的 iteratorEnumeration 方法的问题是一旦您获得了关键迭代器,您就应该对其进行迭代,每次都从地图中获取值。你不需要打电话 hMap.elements();