Reputation: 1952
Since there is known fact that Java generates around 4 Billion unique Hashcodes.
I am using Hashcode of Some String (Example Fname + Lname + DOB + DATE) which becomes Primary Key of my Database
in @PrePersist I set it with Hashcode which helps me in generating Hashcode for new Users. (Which has to be unique).
Now I am running out of has codes. Possible alternative for me is to use SHA-2 , MD5 etc.
How can I increase size of hash code & yet avoid that big collisions.
Upvotes: 0
Views: 403
Reputation: 8324
I think you are confused about using int Object.hashCode(), which you can override and which returns an int and using a secure hash function. Those are two things. Object.hashCode is not intended to return unique integers (returning 1 is a valid implementation). So, using String.hashCode() for object identity is not a great idea since it can and will have collisions. It's intended for use with e.g. HashTables; which means it is optimized for performance and not for avoiding collisions.
You can indeed use sha1, sha2, sha3, or md5 if you want some kind of content hash. If not, use SecureRandom or UUID to generate something random. All of these have a very low probability of ever giving you a collision (not completely 0 of course).
Upvotes: 1
Reputation: 10094
If your goal is to create a unique identifier for the database, I would suggest using UUID.
UUID Version 3, as it uses a namespace, will fit your case.
Some databases have native support for UUID, for instance PostgreSQL
Upvotes: 2