How can I hash composite classes?
Let Abstract
be an abstract class, and A1,A2,...,An
concrete classes that inherit from Abstact
. Each one of Ai
has a list of Abstract
and a pre-defined, known at compile time, set of primitive types, let's assume we have a hush function for them, and there are no 'loops' in the structure of each concrete element.
Two elements e1 and e2 are identical if they have the same values for the predefined primitives, and if for each Abstract
in e1, there exists an Abstract
in e2 such that e1 and e2 are identical. (in other words, order is not important).
I am looking for a good hash heuristic for this kind of problem. It shouldn't (and as far as I k开发者_运维知识库now, can't be) a perfect hash function, but it should be good and easy to compute at run time.
I'll be glad if someone can give me some guidelines how to implement such a function, or direct me to an article that addresses this problem.
PS I am writing in Java, and I assume (correct me if I am wrong) the built in hash()
won't be good enough for this problem.
If these lists can change after they are constructed, it would be a bad idea to base the hash function on them. Imagine if you stuck your object into a HashMap
, and then changed part of it. You would no longer be able to locate it in the HashMap
because its hashCode
would be different.
You should only base the result of hashCode
on immutable values. If you don't have any immutable values in your object, your best bet would probably be to simply use the basic Object.hashCode()
, although you'll lose out on equality testing.
If these objects are immutable, however, then I recommend choosing some kind of sort order for your elements. Then you can compute a hash code across your lists, knowing that it will be the same even if the lists are in different orders, because you are sorting the values before hashing.
Use Google Guava's utilities... Objects.hashCode() is great. Also, the source is available, and they have solved the problem you state, so you can take a look at their solution.
精彩评论