I want to compare two Java Maps by a simple hash.
Each object is on a different computer, so sending a hash over the network will be cheaper that sending the whole object to compare.
For example I have two HashMaps of an ExampleClass
Map<String,ExampleClass> One=new ...;
Map<String,ExampleClass> Other=new ...;
I don’t need to be sure that all elements are equal,
it’s enough for me to trust in a hash.
I was about to iterate at each side and create a “homemade Hash”, then send it to the network to finally compare for example an int or something.
It would be great if this “hash” is calculated every time an object is added or deleted from the Collection, saving me from iterate the whole object. I have to encapsulate every add/delete of the Map. Is there a Java library that does this?
If all your classes implement
hashCode()(does not use the “default” memory address hashcode) you can use the map’shashCode().The caveat here is that if your
ExampleClassdoes not implementhashCode(), then equal items might have different hashes on the two different machines, which will result in different hashes for the maps.To clarify:
Mapimplements ahashCode()that is defined as the sum of it’sMap.Enytry‘shashCode()s.Map.Entry‘shashCode()is defined to be the xor of the key’shashCode()and the value’shashCode().Your keys are
Strings — they have a well definedhashCode()(two equal strings always have the samehashCode()).Your values are
ExampleClassinstances — they also need a well-definedhashCode().In summary, a map that contains
{ s1 -> ec1, s2 -> ec2 }will have a hashcode equal to:meaning that it depends on
ExampleClass‘shashCode().If
ExampleClassdid implementhashCode()in a way that equalExampleClasses give equalhashCode()s, everything will work well.If
ExampleClassdid not implementhashCode(), it will useObject‘shashCode(), which will almost always give you differenthashCodes().