如何获取 LinkedHashMap 的 keyIterator?
通过查看Sun的LinkedHashMaps的源代码,我发现有一个名为KeyIterator的私有类,我想使用它。 我怎样才能获得访问权限?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以通过调用来获得它
,你甚至不需要知道它的存在; 它只是实现的产物。 据您所知,他们可能使用会飞的猴子来迭代密钥; 只要它们按照规范进行迭代,它们如何做并不重要。
顺便说一句,您是否知道
HashMap
有一个名为KeyIterator
的私有类(ConcurrentHashMap
、ConcurrentSkipListMap
也是如此)EnumMap
、IdentityHashMap
、TreeMap
和WeakHashMap
)?这会对您迭代 HashMap 的键的方式产生影响吗?
编辑:在回复您的评论时,请注意,如果您尝试迭代
Map
中的所有键值对,则有这是比迭代键并为每个键调用get
更好的方法。entrySet()
方法获取所有键值对的
Set
,然后您可以对其进行迭代。 因此,您不应编写:您应该编写:
您还可以使用
values()
如果你愿意的话。请注意,由于
keySet
、entrySet
和values
是在Map
接口,它们适用于任何Map
,而不是只是LinkedHashMap
。You get it by calling
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 calledKeyIterator
(as doConcurrentHashMap
,ConcurrentSkipListMap
,EnumMap
,IdentityHashMap
,TreeMap
, andWeakHashMap
)?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 callingget
for each. TheentrySet()
method gets aSet
of all key-value pairs which you can then iterate over. So instead of writing:you should write:
You could also iterate over the values with
values()
if you want.Note that since
keySet
,entrySet
, andvalues
are defined in theMap
interface, they will work for anyMap
, not justLinkedHashMap
.这是一个私有类,所以你不能直接使用它。
当您使用普通迭代器时,会返回它的一个实例。
It's a private class, so you can't directly use it.
An instance of it is returned when you use the normal Iterator.
您不应该使用定义为 LinkedHashMap 内部实现的一部分的任何内容(即在源代码中但未在 API 中定义)。 如果下一个版本中内部实现发生变化会发生什么? 使用它的所有代码都会中断。
您应该编写 API 并执行就像是
You shouldn't use anything that is defined as part of the internal implementation of LinkedHashMap (i.e. in the source code but not defined in the API). What happens if the internal implementation changes in the next release? All of your code using it will break.
You should code to the API and do something like