问题描述
我知道 Hashtable
对象不能接受键或值条目的 null
值,它是同步集合,并且它使用的内存比 HashMap
略少.
I understand that a Hashtable
object cannot accept null
values for either key or value entries, that it is synchronized collection, and that it uses slightly less memory than a HashMap
.
我想知道在哪些情况下使用 Hashtable
而不是 HashMap
更合适.
I'm wondering about the scenarios where it would be more appropriate to use a Hashtable
instead of a HashMap
.
推荐答案
嗯,真的……
我想知道在哪些情况下使用 Hashtable
而不是 HashMap
更合适.
正是当您想要两者之间的差异时:
Precisely when you want the differences between the two:
- 当您想在 Java 1.1 上运行时
- 当您希望每个操作同步时(获得线程安全的形式,只要您从不对其进行迭代) - 并且出于某种原因不想使用
Collections.synchronizedMap
在HashMap
上 - 当您不想存储空值时
- 当内存差异实际上很显着时(只有在您证明是这种情况之后)- 我个人什至没有意识到这种差异......
- 当你被一个返回或接受
Hashtable
的讨厌的 API 逼迫时(幸运的是,相对罕见)
- When you want to run on Java 1.1
- When you want each operation to be synchronized (getting you a form of thread safety, so long as you never iterate over it) - and for some reason don't want to use
Collections.synchronizedMap
over aHashMap
- When you don't want to be able to store null values
- When the memory difference is actually significant (only after you've proved this is the case) - I wasn't even aware of this difference, personally...
- When you're forced to by a nasty API which returns or takes
Hashtable
(relatively rare, fortunately)
我个人不记得上次遇到这种情况是什么时候了 - 我想说在现代 Java 代码中使用 Hashtable
是非常罕见的.
I can't remember the last time I was in that situation, personally - I would say it's vanishingly rare to be appropriate to use Hashtable
in modern Java code.
这篇关于何时应该使用 Hashtable 与 HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!