HashTable 如何排序值?

How does HashTable Order Values?

我想知道哈希表在使用 Put 方法后如何对其值进行排序。

例如:

a         b           c       d                   e
Normal    2 weeks     Next    Save and Finish     Go to Cases

hashtable.put("a","Normal"); ...

值的顺序会有所不同,与我们放置的顺序不同。 我认为顺序是这样的:

b         a        e              c         d                     
2 weeks   Normal   Go to Cases    Next      Save and Finish 

请提出解决问题的数据结构。

谢谢。

在这些情况下,答案通常是 in the documentation:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

如前所述,哈希表的迭代顺序是随意的。如果要保留插入顺序,请使用 LinkedHashMap。如果要获得自然顺序或预定义顺序,请使用 TreeMap。作为自然顺序,我指的是键的顺序,例如 String、Integer、Long 等,作为实现 Comparable 接口,将自动排序为实现 Comparable 的任何其他 class。 Comparator 也可以提供预定义顺序,创建 TreeMap。

类似于HashMap, HashTable也不保证元素的插入顺序。

原因
HashTable 针对快速查找进行了优化。这是通过计算存储的键值的散列来实现的。这确保了在 HashTable 中搜索任何值的时间复杂度为 O(1),无论 HashTable.

中的条目数如何,都需要相同的时间

因此,条目是根据为密钥生成的哈希值存储的。这就是为什么 HashTable 不保证插入元素的顺序的原因。

A hash value (or simply hash), also called a message digest, is a number generated from a string of text. The hash is substantially smaller than the text itself, and is generated by a formula in such a way that it is extremely unlikely that some other text will produce the same hash value.

http://www.webopedia.com/TERM/H/hashing.html
http://interactivepython.org/runestone/static/pythonds/SortSearch/Hashing.html