Java 的 hashmap:keys() 确实丢失了吗?
Java 的 HashTable
是一个同步哈希表(并且存在了相当长一段时间),而 HashMap
是一个非同步的。
在 HashTable
中,有两种方法获取哈希表的键:
键 其中:
键
public Enumerationkeys()返回键的枚举 这个哈希表。
和
公共设置 keySet()
返回此中包含的键的集合视图 哈希表。该集合由哈希表支持,因此更改为 Hashtable 反映在 Set 中,反之亦然。该套装支持 元素删除(从 Hashtable),但不是元素添加。
在后者中,明确指出键是对哈希表的直接引用(因此要注意修改等)。
但是对于keys()
却没有这样的提及。
所以我的问题是:
使用枚举器的 keys()
是否返回键的副本(与返回实际键的 keyset()
不同)?
如果是的话,为什么HashMap
中没有这样的方法而只提供了keyset()
?
Java's HashTable
is a synchronized hashtable (and exists for quite a while) while HashMap
is an unsynchronized.
In HashTable
there are 2 ways to get the keys of the hashtable:
Keys which:
key
public Enumeration keys()Returns an enumeration of the keys in
this hashtable.
and
public Set keySet()
Returns a Set view of the keys contained in this
Hashtable. The Set is backed by the Hashtable, so changes to the
Hashtable are reflected in the Set, and vice-versa. The Set supports
element removal (which removes the corresponding entry from the
Hashtable), but not element addition.
In the latter it is explicitely stated that the keys are direct references to the hashtable (so beware of modifications etc).
But there is no such mention for the keys()
.
So my question is:
Does the keys()
using an enumerator return a copy of the keys (unlike keyset()
which return the actual keys)?
And if yes why there is no such method in HashMap
and only keyset()
is provided?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Hashtable.keys 返回对真实键的引用。它不会复制它们。
HashMap 中不存在该方法,因为 keySet 已经完成了这项工作。它存在于 hashtable 中是因为这个类从 java 1.0 就已经存在了。直到 1.2 才添加定义 keySet 方法的集合框架。
Hashtable.keys returns references to the real keys. It does not copy them.
The method does not exist in HashMap because keySet already does the job. It exists in hashtable because this class has been around since java 1.0. The collections framework that defines the keySet method wasn't added until 1.2.
一般来说,非同步集合上的迭代器表现得不是特别好(它们往往会抛出 ConcurrentModificationException 或以未指定的方式运行)
。 grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Hashtable.java#Hashtable.keys%28%29" rel="nofollow">查看Hashtable的源码,可以看到键集的迭代器和keys()枚举实际上是由同一个内部类实现的,如果哈希表发生变化。所以,不,它不会复制密钥。
In general Iterators on unsynchronized collections don't behave particularly well (they tend to throw
ConcurrentModificationException
or behave in an unspecified manner)By looking at the source code for Hashtable, you can see that the key set's iterator and keys() enumeration are in fact implemented by the same inner class, which will attempt to throw a ConcurrentModificationException if the Hashtable changes. So, no, it is not going to make a copy of the keys.