1
The methods you used were for returning longs. The method you should use is String.hashCode() if you don’t need hashing for security purposes. Make sure to cast an integer as a String through String.valueOf(int) before hashing it, since you said you want to hash ints as well.
int hash = String.valueOf(input).hashCode();
2
Edit: Added MD5 info after OP requested in comment
I have a class that can take an input String, process it through MD5, and convert it to a long, though I don’t know how to convert it to an int. What you can do is return the long, and truncate it to only 10 characters for an int. Here is the class:
import java.security.*;
public class HX {
final String seed;
final MessageDigest md;
final long hash;
public HX(String s) throws NoSuchAlgorithmException {
seed = s;
md = MessageDigest.getInstance("MD5");
hash = computeHash();
}
public long getHash() {
return hash;
}
public long computeHash() {
md.reset();
final byte[] digest = md.digest(seed.getBytes());
return (computeHash(digest, 0) ^ computeHash(digest, 8));
}
private static final long computeHash(final byte[] array, final int offset) {
long value = 0;
for (int i = 0; i < 8; i++) {
value = ((value << 8) | (array[offset+i] & 0xFF));
}
return value;
}
}
It could still exceed the MAX_VALUE after truncation, however, so if that’s the case, you’d need to truncate it an int of length 9.
long longHash = 0;
try {
HX h = new HX(seed);
longHash = h.getHash();
} catch(Exception e) {
e.printStackTrace();
}
try {
int hash = Integer.parseInt(longHash.substring(0,9));
} catch(Exception e) {
int hash = Integer.parseInt(longHash.substring(0,8));
}
3
If you’d like an alternative to MD5, I have a method I downloaded a long time ago from a post by a guy claiming that his “better hash” reduced collisions; some tests with a list of thousands of dictionary words appeared to have confirmed this, from what I recall.
public static int hash(String s) {
int hash = 0;
for (int i = 0; i < s.length(); i++) {
hash = 257*hash + s.charAt(i);
}
return h;
}
9
solved Java hashing function to return int that does not exceed Integer.MAX_VALUE [closed]