通过哈希算法可以实现布隆过滤器, 一致性哈希,解决工程中的问题。
import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Locale;
public class Code_Hash {
private MessageDigest hash;
public Code_Hash(String algorithm){
try {
hash = MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public String hashCode(String input){
return DatatypeConverter.printHexBinary(hash.digest(input.getBytes())).toUpperCase();
}
public static void main(String[] args) {
System.out.println("支持的算法");
for (String str: Security.getAlgorithms("MessageDigest")) {
System.out.println(str);
}
String algorithm = "MD5";
Code_Hash hash = new Code_Hash(algorithm);
String input1 = "heikediguo1";
String input2 = "heikediguo2";
String input3 = "heikediguo3";
String input4 = "heikediguo4";
String input5 = "heikediguo5";
System.out.println(hash.hashCode(input1));
System.out.println(hash.hashCode(input2));
System.out.println(hash.hashCode(input3));
System.out.println(hash.hashCode(input4));
System.out.println(hash.hashCode(input5));
}
}