import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.Random;
import java.util.List;
/**
* @description:
* @author: wukong
* @remark: create wukong 2019/12/26 22:49
*/
public class HashTest {
public static void main(String[] args) {
int length = 1 << 8;
List<Double> doubles = new ArrayList<>(100);
List<Double> double2s = new ArrayList<>(100);
// 测试次数
int count = 100;
for (int i = 0; i < count; i++) {
hashCalculate(length, doubles, double2s);
}
System.out.println("均值1:" + doubles.stream().mapToDouble((item) -> item).summaryStatistics().getAverage());
System.out.println("均值2:" + double2s.stream().mapToDouble((item) -> item).summaryStatistics().getAverage());
System.out.println("集合1:" + JSON.toJSON(doubles));
System.out.println("集合2" + JSON.toJSON(double2s));
}
/**
* @Description: hash碰撞率计算
*/
private static void hashCalculate(int length, List<Double> doubles, List<Double> double2s) {
int cardinal = length - 1;
int load = (int) (length * 0.75);
int crash = 0;
int crash2 = 0;
List<Integer> list = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
for (int0 = I; I <Load; I ++ ) {
// random key hash value acquired
int the hash = getRandomString () the hashCode ();.
// ANDed direct radix
int Result = & Cardinal the hash;
// jdk8 in hashmap perturbation function
int disturbHash the hash ^ = (the hash >>> 16 );
// value calculating perturbed
int result2 = Cardinal & disturbHash;
// count the number of collisions is directly operation
IF (! list.contains (Result)) {
List. the Add (Result);
} the else {
Crash ++ ;
}
// the number of collisions statistic disturbing
IF (! {List2.contains (result2))
list2.add (result2);
} the else {
crash2 ++ ;
}
}
Double crashProbability = Crash / ( Double ) length;
Double crashProbability2 = crash2 / ( Double ) length;
doubles.add (crashProbability);
double2s.add (crashProbability2);
// System.out.println ( "when the length" + length + "when, hash value calculation direct collision rate:" + crashProbability);
// System.out.println ( "when the length" + length + "When, after the disturbance function and the operation rate of the collision:" + crashProbability2);
}
/ **
* @Description: to obtain random key string
* /
Private static String getRandomString () {
String STR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ;
the Random Random = new new the Random ();
the StringBuffer SB = new new the StringBuffer ();
int length =. 8 ;
for ( int I = 0; I <length; I ++ ) {
int Number = Random .nextInt (62 );
sb.append(str.charAt(number));
}
return sb.toString();
}
}