In Java 6, my understanding is that you can supply a Comparator to a TreeSet when creating it to override the "natural ordering" of the objects in the set.
Do you have any thoughts why Java doesn't support supplying a "Hasher" that overrides the "natural hashing" of objects in the set as well?
EDIT: Getting开发者_StackOverflow中文版 input from you might help me when designing APIs in the future.
Thanks.
Here are several likely reasons:
Simplicity - most people don't need multiple hash functions, so to keep the API simple it makes sense to rely on a single Object.hashCode() approach
Performance - In the standard library at least, HashSets and HashMaps etc. need to be pretty heavily optimised as they are so widely used. It doesn't make sense to have the overhead of calling a separate "hasher", however small that overhead may be.
Private fields - there is the issue that hashCode() may rely on private fields, it may be difficult to create external "hashers" for some objects.
A Hasher
object would be redundant to the hashCode()
method in the Object
class.
If you want to effect the nature of the hashing, you should override the hashCode()
method defined on Object
. Just be sure to override equals(Object)
as well, since these two should always go together.
A HashSet
or other similar data structure will use the objects hashCode()
method to get a hash value to determine bin storage. It will then use equals()
to compare that object to other objects in the same bin to determine equality.
The hash code generated needs to be unique to that specific class of object. This can be ensured simply by overriding the hashCode()
method and doesn't need to change from implementation to implementation. A Hasher
object would just obfuscate and serve no additional purpose. I couldn't think of a single use case where multiple hash codes would be needed for storage in different data structures.
It does! Check out the Object.hashCode method.
After reading your question again I might have jumped the gun. I now see that you said "override" the natural hshing. Usually we override the hash value at the object level and forgo the use of a overriding Hasher.
Hashes are meant to be more universal that comparators. That is, hashes should almost always create uniform distrusted values with little chance of collision. The container in which they are used should rarely need a specialized hasher.
It has already been asked.
You can change the hash code of an object by wrapping in an Object which inplements hash code your way. The assumption is that you may want to have a objects sorted a numebr of ways, but not have multiple hashing strategies.
c.f. Trove4j supports hashing strategies for its HashMap and while I use this library often I have only used a custom hashing strategy once I can remember.
精彩评论