4

I'm trying to get an ID from a String in Java, and I thought I would use hashcode (Yeah, two strings can have the same hashcode but I can live with that small probability). I want this ID to have a max of 4 digits. Is that possible?

This is the String default hashCode implementation:

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

Can I override it to produce a hash with 4 digits?

12
  • 4
    return h % 10000; should work Commented Aug 3, 2018 at 15:50
  • 1
    Just like you can have any number represented in 4 digits. The remainder. Commented Aug 3, 2018 at 15:50
  • 1
    Sure, you can @Override any inherited method that is not final nor private. However, what is the meaning of reducing the length of the hash code to 4 digits? Commented Aug 3, 2018 at 15:51
  • 1
    @IlyaBursov except h can be negative… Commented Aug 3, 2018 at 16:49
  • 1
    @shmosel it cannot be min value after modulo Commented Aug 7, 2018 at 18:19

1 Answer 1

1

One simple trick is to just take the last four digits:

private static int myHash(String s) {
    return s.hashCode() % 10000;
}

EDIT:
As @Holger commented, hashCode() may return a negative value. If the requirement is to return a positive four-digit integer, you could take the absolute value:

private static int myHash(String s) {
    return Math.abs(s.hashCode() % 10000);
}
Sign up to request clarification or add additional context in comments.

9 Comments

Why the static?
@Nikolas why not?
Of course, you now only have 10,000 has code values, so the probability of collision is much higher than before,
@Nikolas again - why not? You're not using any instance member here, so why push the this pointer needlessly in the stack?
@Nikolas The OP's code example is an instance method because it's the JDK source code for String.hashCode. (String is a final class, so we aren't talking about extending and overriding hashCode, nor should we ever override hashCode like this even in cases where we can, because of the Liskov Substitution Principle and contractual obligations in general.) With respect, your criticism doesn't make much sense. Utility methods like this are usually static.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.