简体   繁体   中英

Java's hashmap: Is keys() indeed missing?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM