Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

java - When should I use a Hashtable versus a HashMap

This is not a question about the differences between Hashtable and 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.

I'm wondering about the scenarios where it would be more appropriate to use a Hashtable instead of a HashMap.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is not a question about the differences between Hashtable and HashMap

Well it is really...

I'm wondering about the scenarios where it would be more appropriate to use a Hashtable instead of a HashMap.

Precisely when you want the differences between the two:

  • 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 a HashMap
  • 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)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...