Java Hashtable 中的 Set keys() 和 Set keyset() 有什么区别?

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

我正在这个网站上学习集合框架:http://way2java.com/collections/hashtable-about/。在阅读了 Hashtable 的所有方法后,我看到了两种访问 table 键的方法:

  1. Set keys(): Returns 包含所有键的 Set 对象

  2. Set keySet(): Returns 一个包含 Hashtable 的所有键的 Set 对象。一个相似点是 HashtableSet 不允许重复。在 Set 中添加和删除元素也反映在 Hashtable

他们都是return一个Set对象。我看不出他们之间有什么不同。谁能告诉我这件事?

Hashtable中的方法keys()实际上return枚举键:

  Enumeration<K>    keys()

Returns 此哈希表中键的枚举。

keys() 不是 return 一个 Set,它 return 是一个 Enumeration<K>.

Hashtable 是一个很旧的 class 不再推荐使用。它被 HashMapConcurrentHashMap 取代。它在 JCF 之前就存在了,因此在开始时获取键的标准方法是通过 Enumeration - 用于在对象集合中移动的原始 Java 界面。

然后是 Java 1.2 和 JCF. Hashtable was retrofitted for the Map interface with the keySet() method that returned a Set(也与 JCF 一起引入)。 keys 方法因遗留兼容性原因而保留。来自新方法的 Set returned 实现了两件事:

  1. 传达意图 - 它强化了一个事实,即 Hashtable 的键是一个数学集合
  2. 实现 Iterable<T>,它取代了 Enumerable<T>

来自 Hashtable 文档:

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.

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界面。

keys()存在于原来的Hashtable和returns一个Enumaration of keys. keySet() is more modern method that was introduced in the Map interface and returns a Set的键中。