Using Java Dictionary…use a Hashtable?

痴心易碎 提交于 2020-02-23 09:52:08

问题


I'm a bit surprised no one has asked about this specific case, cause it's kind of a weird inconsistency in the java standard libraries:

I'm using swing JSliders with custom labels; the only library call available to assign labels is: setLabelTable(Dictionary labels)

But Dictionary is an abstract class, and its only known subclass in the standard lib is Hashtable, which the api & various IDE's complain about because it's "obsolete."

The obvious thing to do is just use the Hashtable, but I'm wondering two things:

  1. Is there a better way to approach this?
  2. If Hashtable is the only usable class for this (in my opinion) reasonably important library call, on what basis is it "obsolete"?

Thanks!


回答1:


The reason Hashtable is obsolete is because it was was replaced with Hashmap.

However, for the purposes of assigning labels to a setLabelTable, the "deficiencies" of Hashtable are not a problem.




回答2:


It is obsolete because it has been replaced with java.util.HashMap. The primary differences are that methods on HashTable are synchronized, and HashMap allows use of the null pointer as a key.

Modern versions of java have come a long way in the performance of un-contested synchronized operations, so there isn't really the performance concern that there used to be. (if you're running on up to date JDK on a major platform.) If an API requires a HashTable, go ahead and use it.




回答3:


Dictionary was "replaced" by Map and HashTable by a HashMap.
A HashTable is slow since it is synchronized so HashMap is the norm choice.
I am not sure why you worry that you use a "legacy" datastructure since if you must use a JSlider you have to use the HashMap.
Perhaps you should be wondering about which widgets to use instead? Just a thought...



来源:https://stackoverflow.com/questions/11530661/using-java-dictionary-use-a-hashtable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!