user2133558
user2133558

Reputation: 534

Java String HashCode of n digits?

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?

Upvotes: 4

Views: 2575

Answers (1)

Mureinik
Mureinik

Reputation: 312116

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);
}

Upvotes: 1

Related Questions