Quan Nguyen
Quan Nguyen

Reputation: 696

What is the difference between Set keys() and Set keyset() in Hashtable in Java?

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:

  1. Set keys(): Returns a Set object containing all the keys

  2. 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

Answers (3)

Andy Brown
Andy Brown

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:

  1. conveys intent - it reinforces the fact that the keys of a Hashtable are a mathematical set
  2. implements Iterable<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

Mureinik
Mureinik

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

Tarun Gupta
Tarun Gupta

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

Related Questions