问题
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:
- Is there a better way to approach this?
- 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