How do I get a keyIterator for a LinkedHashMap?

前端 未结 3 1141
误落风尘
误落风尘 2021-02-13 09:43

By looking at the source code for LinkedHashMaps from Sun, I see that there is a private class called KeyIterator, I would like to use this. How can I gain access?

3条回答
  •  伪装坚强ぢ
    2021-02-13 10:25

    You get it by calling

    myMap.keySet().iterator();
    

    You shouldn't even need to know it exists; it's just an artifact of the implementation. For all you know, they could be using flying monkeys to iterate the keys; as long as they're iterated according to the spec, it doesn't matter how they do it.

    By the way, did you know that HashMap has a private class called KeyIterator (as do ConcurrentHashMap, ConcurrentSkipListMap, EnumMap, IdentityHashMap, TreeMap, and WeakHashMap)?
    Does that make a difference in how you iterate through the keys of a HashMap?


    Edit: In reponse to your comment, be aware that if you are trying to iterate over all key-value pairs in a Map, there is a better way than iterating over the keys and calling get for each. The entrySet() method gets a Set of all key-value pairs which you can then iterate over. So instead of writing:

    for (Key key : myMap.keySet()) {
        Value val = myMap.get(key);
        ...
    }
    

    you should write:

    for (Map.Entry entry : myMap.entrySet()) {
        doSomethingWithKey(entry.getKey());
        doSomethingWithValue(entry.getValue());
        ...
    }
    

    You could also iterate over the values with values() if you want.

    Note that since keySet, entrySet, and values are defined in the Map interface, they will work for any Map, not just LinkedHashMap.

提交回复
热议问题