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?
return h % 10000; should work@Overrideany inherited method that is not final nor private. However, what is the meaning of reducing the length of the hash code to 4 digits?hcan be negative…