Hash code for expandable class (future proof)

陌路散爱 提交于 2019-12-11 20:51:47

问题


Since I don't have any great skills in math, I ask you if there exists any algorithm that I should use for a class which probably will change in the future.

Consider following scenario:

Class "Roles" has following fields:

private boolean admin;
private boolean printer;

After some weeks I decide to add a role "guest":

private boolean admin;
private boolean printer;
private boolean guest;

After some weeks I decide to remove the role "printer";

private boolean admin;
private boolean guest;

Since I will persist the hashcode in a database, I must be 100% sure that all versions of this class generates unique hashcodes.

Maybe this is not a problem, I have always used the one provided in the Eclispe IDE source generator.

Can you please tell me if I am safe with the Eclipse IDE (Indigo) Java version >= 6 method or give me some other advices regarding this topic. I am sure this is a very common thing.

Thanks in advance


回答1:


Since I will persist the hashcode in a database

Don't do that. The result of hashCode isn't meant to be persisted. In particular, from the docs:

This integer need not remain consistent from one execution of an application to another execution of the same application.

Next:

I must be 100% sure that all versions of this class generates unique hashcodes.

Hash codes aren't meant to be unique, either... they very often won't be. Okay, you've only got 5 bits of data in your case, but in general that's not the case...

It sounds like you have different requirements from the normal ones for Object.hashCode() - so you shouldn't expect any autogenerated implementation to know about your special requirements. I suggest you state exactly what your requirements are, and we can work out what to do...




回答2:


To give some idea of the difference between 32 bit hashcodes and UUID's, and how likely a collision is per the Birthday Paradox, this is how many ids you would need to generate to get a 50% chance that two of them have the same value (a collision):

32 bit hashcode - 77,000

128 bit UUID - 22,000,000,000,000,000,000

A hashcode does not promise uniqueness, with collisions to be expected in normal use. UUIDs promise practical uniqueness, where collisions are extremely unlikely in practice.

see http://blogs.msdn.com/b/ericlippert/archive/2010/03/22/socks-birthdays-and-hash-collisions.aspx and http://en.wikipedia.org/wiki/Universally_unique_identifier



来源:https://stackoverflow.com/questions/11801733/hash-code-for-expandable-class-future-proof

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