1

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.

1

1 Answer 1

5

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.

5
  • But I need a number as unique id based on object data not a string. What could be other possible way? Dec 30, 2013 at 7:35
  • What's that requirement based on?
    – SBI
    Dec 30, 2013 at 7:36
  • based on email id @SBI Dec 30, 2013 at 7:37
  • isn't there a way I can generate unique Id from email or first name or last name or from combination of other object data members? @EvgeniyDorofeev Dec 30, 2013 at 7:51
  • not as int or long, you can make an integer but you'll need BigInteger Dec 30, 2013 at 7:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.