如何获取LinkedHashMap的keyIterator? [英] How do I get a keyIterator for a LinkedHashMap?

查看:151
本文介绍了如何获取LinkedHashMap的keyIterator?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过查看Sun的LinkedHashMaps的源代码,我发现有一个名为KeyIterator的私有类,我想使用它。我怎样才能获得访问权?

解决方案

你可以通过致电



<$来获得它p $ p> myMap.keySet()迭代();

你甚至不需要知道它存在;它只是实现的一个工件。如你所知,他们可能正在使用飞猴来重复密钥;只要他们根据规范进行迭代,他们是如何做到这一点并不重要。



顺便问一下,你知道吗 HashMap 有一个名为 KeyIterator 的私有类(和 ConcurrentHashMap 一样, ConcurrentSkipListMap EnumMap IdentityHashMap TreeMap WeakHashMap )?

这对于迭代键的方式有所不同吗? HashMap






编辑:在回复评论时,请注意,如果您尝试迭代 Map 中的所有键值对,则有一种比迭代键更好的方法为每个人调用获取 entrySet( ) 方法获得所有键值对的 Set ,然后可以迭代。因此,而不是写:

  for(Key key:myMap.keySet()){
Value val = myMap。获得(键);
...
}

你应该写:

  for(Map.Entry< Key,Value> entry:myMap.entrySet()){
doSomethingWithKey(entry.getKey()) ;
doSomethingWithValue(entry.getValue());
...
}

您还可以使用<来迭代值a href =http://java.sun.com/javase/6/docs/api/java/util/Map.html#values() =noreferrer> values() 如果你想要。



注意,因为 keySet entrySet Map 界面,它们适用于任何地图,而不仅仅是 LinkedHashMap


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?

解决方案

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<Key, Value> 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.

这篇关于如何获取LinkedHashMap的keyIterator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆