MaheshVarma
MaheshVarma

Reputation: 2125

Generate Unique Id based on object data

I am doing a small project where end user enters data into a form (jsp). I read the data and save into User Object, I need to store the user data into a file not into DB. Here each user data is stored as a single line of text in .txt file.

My requirement is to generate a unique id based on contact number and email, currently I am considering email-id to generate hashcode which will be the unique identification number for that user. But I do not want to get -ve values as unique id. I am using the following code to generate `hashcode'.

 static int hashCode(User u) {
    int hash = 37;
    if (u != null) {
        if (u.email != null && u.email.length() > 0) {

            hash = "1@d&$2u".hashCode() + hash
                    + u.email.toLowerCase().hashCode();
        }
    }

    return hash;

}

Am I doing anything wrong here? Is there any other way I can generate unique id for each user object based on email. if two user objects have same email id, then the hashcode must be same for both objects.

Upvotes: 1

Views: 2023

Answers (1)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

Hashcode is not required to be unique even for different values. You should not use it as unique ID. Use email string directly. Email is unique by definition.

If you need a numeric ID then make ID equal to text file line number.

Upvotes: 5

Related Questions