Reputation: 696
I am learning Collection Framework on this website: http://way2java.com/collections/hashtable-about/. After reading all the methods of Hashtable
I see two methods to access the table's keys:
Set keys()
: Returns a Set
object containing all the keys
Set keySet()
: Returns a Set
object containing all the keys of Hashtable
. One similarity is Hashtable
and Set
does not allow duplicates. Adding and removing elements in Set
also reflects in Hashtable
Both of them return a Set
object. I don't see the different between them. Anyone can tell me about this?
Upvotes: 0
Views: 1386
Reputation: 19161
keys()
doesn't return a Set
, it returns an Enumeration<K>
.
Hashtable
is a very legacy class no longer recommended for use. It is replaced by HashMap
, or ConcurrentHashMap
†. It existed before the JCF did, therefore the standard way to get to the keys at the start was through an Enumeration
- the original Java interface for moving through a collection of objects.
Then came Java 1.2, and the JCF. Hashtable
was retrofitted for the Map
interface with the keySet()
method that returned a Set
(also introduced with the JCF). The keys
method was retained for legacy compatibility reasons. The Set
returned from the new method achieves two things:
Hashtable
are a mathematical setIterable<T>
, which replaces Enumerable<T>
† From the Hashtable
documentation:
As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.
Upvotes: 3
Reputation: 311573
Hashtable
is an old, outdated, class that existed in Java before the introduction of the standard collections framework in Java 1.2(!), and was retrofitted to adhere to the Map
interface.
keys()
existed in the original Hashtable
and returns an Enumaration
of keys. keySet()
is more modern method that was introduced in the Map
interface and returns a Set
of the keys.
Upvotes: 1
Reputation: 1669
The method keys() in Hashtable actually return Enumeration of keys:
Enumeration<K> keys()
Returns an enumeration of the keys in this hashtable.
Upvotes: 1