Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

java - Hash code for expandable class (future proof)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...