Java实现的hash算法实现大全,供大家参考

  1. /**  
  2. * Hash算法大全<br>  
  3. * 推荐使用FNV1算法  
  4. * @algorithm None  
  5. * @author Goodzzp 2006-11-20  
  6. * @lastEdit Goodzzp 2006-11-20   
  7. * @editDetail Create  
  8. */   
  9. public   class  HashAlgorithms  
  10. {  
  11. /**  
  12. * 加法hash  
  13. * @param key 字符串  
  14. * @param prime 一个质数  
  15. * @return hash结果  
  16. */   
  17. public   static   int  additiveHash(String key,  int  prime)  
  18. {  
  19.    int  hash, i;  
  20.    for  (hash = key.length(), i =  0 ; i < key.length(); i++)  
  21.     hash += key.charAt(i);  
  22.    return  (hash % prime);  
  23. }  
  24.   
  25. /**  
  26. * 旋转hash  
  27. * @param key 输入字符串  
  28. * @param prime 质数  
  29. * @return hash值  
  30. */   
  31. public   static   int  rotatingHash(String key,  int  prime)  
  32. {  
  33.    int  hash, i;  
  34.    for  (hash=key.length(), i= 0 ; i<key.length(); ++i)  
  35.      hash = (hash<<4 )^(hash>> 28 )^key.charAt(i);  
  36.    return  (hash % prime);  
  37. //   return (hash ^ (hash>>10) ^ (hash>>20));   
  38. }  
  39.   
  40. // 替代:   
  41. // 使用:hash = (hash ^ (hash>>10) ^ (hash>>20)) & mask;   
  42. // 替代:hash %= prime;   
  43.   
  44.   
  45. /**  
  46. * MASK值,随便找一个值,最好是质数  
  47. */   
  48. static   int  M_MASK =  0x8765fed1 ;  
  49. /**  
  50. * 一次一个hash  
  51. * @param key 输入字符串  
  52. * @return 输出hash值  
  53. */   
  54. public   static   int  oneByOneHash(String key)  
  55. {  
  56.    int    hash, i;  
  57.    for  (hash= 0 , i= 0 ; i<key.length(); ++i)  
  58.    {  
  59.      hash += key.charAt(i);  
  60.      hash += (hash << 10 );  
  61.      hash ^= (hash >> 6 );  
  62.    }  
  63.    hash += (hash << 3 );  
  64.    hash ^= (hash >> 11 );  
  65.    hash += (hash << 15 );  
  66. //   return (hash & M_MASK);   
  67.    return  hash;  
  68. }  
  69.   
  70. /**  
  71. * Bernstein's hash  
  72. * @param key 输入字节数组  
  73. * @param level 初始hash常量  
  74. * @return 结果hash  
  75. */   
  76. public   static   int  bernstein(String key)  
  77. {  
  78.    int  hash =  0 ;  
  79.    int  i;  
  80.    for  (i= 0 ; i<key.length(); ++i) hash =  33 *hash + key.charAt(i);  
  81.    return  hash;  
  82. }  
  83.   
  84. //   
  85.  Pearson's Hash   
  86. // char pearson(char[]key, ub4 len, char tab[256])   
  87. // {   
  88. //   char hash;   
  89. //   ub4 i;   
  90. //   for (hash=len, i=0; i<len; ++i)    
  91. //     hash=tab[hash^key[i]];   
  92. //   return (hash);   
  93. // }   
  94.   
  95.  CRC Hashing,计算crc,具体代码见其他   
  96. // ub4 crc(char *key, ub4 len, ub4 mask, ub4 tab[256])   
  97. // {   
  98. //   ub4 hash, i;   
  99. //   for (hash=len, i=0; i<len; ++i)   
  100. //     hash = (hash >> 8) ^ tab[(hash & 0xff) ^ key[i]];   
  101. //   return (hash & mask);   
  102. // }   
  103.   
  104. /**  
  105. * Universal Hashing  
  106. */   
  107. public   static   int  universal( char []key,  int  mask,  int [] tab)  
  108. {  
  109.    int  hash = key.length, i, len = key.length;  
  110.    for  (i= 0 ; i<(len<< 3 ); i+= 8 )  
  111.    {  
  112.      char  k = key[i>> 3 ];  
  113.      if  ((k& 0x01 ) ==  0 ) hash ^= tab[i+ 0 ];  
  114.      if  ((k& 0x02 ) ==  0 ) hash ^= tab[i+ 1 ];  
  115.      if  ((k& 0x04 ) ==  0 ) hash ^= tab[i+ 2 ];  
  116.      if  ((k& 0x08 ) ==  0 ) hash ^= tab[i+ 3 ];  
  117.      if  ((k& 0x10 ) ==  0 ) hash ^= tab[i+ 4 ];  
  118.      if  ((k& 0x20 ) ==  0 ) hash ^= tab[i+ 5 ];  
  119.      if  ((k& 0x40 ) ==  0 ) hash ^= tab[i+ 6 ];  
  120.      if  ((k& 0x80 ) ==  0 ) hash ^= tab[i+ 7 ];  
  121.    }  
  122.    return  (hash & mask);  
  123. }  
  124.   
  125. /**  
  126. * Zobrist Hashing  
  127. */    
  128. public   static   int  zobrist(  char [] key, int  mask,  int [][] tab)  
  129. {  
  130.    int  hash, i;  
  131.    for  (hash=key.length, i= 0 ; i<key.length; ++i)  
  132.      hash ^= tab[i][key[i]];  
  133.    return  (hash & mask);  
  134. }  
  135.   
  136. // LOOKUP3    
  137. // 见Bob Jenkins(3).c文件   
  138.   
  139. // 32位FNV算法   
  140. static   int  M_SHIFT =  0 ;  
  141. /**  
  142. * 32位的FNV算法  
  143. * @param data 数组  
  144. * @return int值  
  145. */   
  146.     public   static   int  FNVHash( byte [] data)  
  147.     {  
  148.         int  hash = ( int )2166136261L;  
  149.         for ( byte  b : data)  
  150.             hash = (hash * 16777619 ) ^ b;  
  151.         if  (M_SHIFT ==  0 )  
  152.             return  hash;  
  153.         return  (hash ^ (hash >> M_SHIFT)) & M_MASK;  
  154.     }  
  155.     /**  
  156.      * 改进的32位FNV算法1  
  157.      * @param data 数组  
  158.      * @return int值  
  159.      */   
  160.     public   static   int  FNVHash1( byte [] data)  
  161.     {  
  162.         final   int  p =  16777619 ;  
  163.         int  hash = ( int )2166136261L;  
  164.         for ( byte  b:data)  
  165.             hash = (hash ^ b) * p;  
  166.         hash += hash << 13 ;  
  167.         hash ^= hash >> 7 ;  
  168.         hash += hash << 3 ;  
  169.         hash ^= hash >> 17 ;  
  170.         hash += hash << 5 ;  
  171.         return  hash;  
  172.     }  
  173.     /**  
  174.      * 改进的32位FNV算法1  
  175.      * @param data 字符串  
  176.      * @return int值  
  177.      */   
  178.     public   static   int  FNVHash1(String data)  
  179.     {  
  180.         final   int  p =  16777619 ;  
  181.         int  hash = ( int )2166136261L;  
  182.         for ( int  i= 0 ;i<data.length();i++)  
  183.             hash = (hash ^ data.charAt(i)) * p;  
  184.         hash += hash << 13 ;  
  185.         hash ^= hash >> 7 ;  
  186.         hash += hash << 3 ;  
  187.         hash ^= hash >> 17 ;  
  188.         hash += hash << 5 ;  
  189.         return  hash;  
  190.     }  
  191.   
  192.     /**  
  193.      * Thomas Wang的算法,整数hash  
  194.      */    
  195.     public   static   int  intHash( int  key)  
  196.     {  
  197.       key += ~(key << 15 );  
  198.       key ^= (key >>> 10 );  
  199.       key += (key << 3 );  
  200.       key ^= (key >>> 6 );  
  201.       key += ~(key << 11 );  
  202.       key ^= (key >>> 16 );  
  203.       return  key;  
  204.     }  
  205.     /**  
  206.      * RS算法hash  
  207.      * @param str 字符串  
  208.      */   
  209.     public   static   int  RSHash(String str)  
  210.     {  
  211.         int  b    =  378551 ;  
  212.         int  a    =  63689 ;  
  213.         int  hash =  0 ;  
  214.   
  215.        for ( int  i =  0 ; i < str.length(); i++)  
  216.        {  
  217.           hash = hash * a + str.charAt(i);  
  218.           a    = a * b;  
  219.        }  
  220.   
  221.        return  (hash &  0x7FFFFFFF );  
  222.     }  
  223.     /* End Of RS Hash Function */   
  224.   
  225.     /**  
  226.      * JS算法  
  227.      */   
  228.     public   static   int  JSHash(String str)  
  229.     {  
  230.        int  hash =  1315423911 ;  
  231.   
  232.        for ( int  i =  0 ; i < str.length(); i++)  
  233.        {  
  234.           hash ^= ((hash << 5 ) + str.charAt(i) + (hash >>  2 ));  
  235.        }  
  236.   
  237.        return  (hash &  0x7FFFFFFF );  
  238.     }  
  239.     /* End Of JS Hash Function */   
  240.   
  241.     /**  
  242.      * PJW算法  
  243.      */   
  244.     public   static   int  PJWHash(String str)  
  245.     {  
  246.         int  BitsInUnsignedInt =  32 ;  
  247.         int  ThreeQuarters     = (BitsInUnsignedInt *  3 ) /  4 ;  
  248.         int  OneEighth         = BitsInUnsignedInt /  8 ;  
  249.         int  HighBits          =  0xFFFFFFFF  << (BitsInUnsignedInt - OneEighth);  
  250.         int  hash              =  0 ;  
  251.         int  test              =  0 ;  
  252.   
  253.        for ( int  i =  0 ; i < str.length();i++)  
  254.        {  
  255.           hash = (hash << OneEighth) + str.charAt(i);  
  256.   
  257.           if ((test = hash & HighBits) !=  0 )  
  258.           {  
  259.              hash = (( hash ^ (test >> ThreeQuarters)) & (~HighBits));  
  260.           }  
  261.        }  
  262.   
  263.        return  (hash &  0x7FFFFFFF );  
  264.     }  
  265.     /* End Of P. J. Weinberger Hash Function */   
  266.   
  267.     /**  
  268.      * ELF算法  
  269.      */   
  270.     public   static   int  ELFHash(String str)  
  271.     {  
  272.         int  hash =  0 ;  
  273.         int  x    =  0 ;  
  274.   
  275.        for ( int  i =  0 ; i < str.length(); i++)  
  276.        {  
  277.           hash = (hash << 4 ) + str.charAt(i);  
  278.           if ((x = ( int )(hash & 0xF0000000L)) !=  0 )  
  279.           {  
  280.              hash ^= (x >> 24 );  
  281.              hash &= ~x;  
  282.           }  
  283.        }  
  284.   
  285.        return  (hash &  0x7FFFFFFF );  
  286.     }  
  287.     /* End Of ELF Hash Function */   
  288.   
  289.     /**  
  290.      * BKDR算法  
  291.      */   
  292.     public   static   int  BKDRHash(String str)  
  293.     {  
  294.         int  seed =  131// 31 131 1313 13131 131313 etc..   
  295.         int  hash =  0 ;  
  296.   
  297.        for ( int  i =  0 ; i < str.length(); i++)  
  298.        {  
  299.           hash = (hash * seed) + str.charAt(i);  
  300.        }  
  301.   
  302.        return  (hash &  0x7FFFFFFF );  
  303.     }  
  304.     /* End Of BKDR Hash Function */   
  305.   
  306.     /**  
  307.      * SDBM算法  
  308.      */   
  309.     public   static   int  SDBMHash(String str)  
  310.     {  
  311.         int  hash =  0 ;  
  312.   
  313.        for ( int  i =  0 ; i < str.length(); i++)  
  314.        {  
  315.           hash = str.charAt(i) + (hash << 6 ) + (hash <<  16 ) - hash;  
  316.        }  
  317.   
  318.        return  (hash &  0x7FFFFFFF );  
  319.     }  
  320.     /* End Of SDBM Hash Function */   
  321.   
  322.     /**  
  323.      * DJB算法  
  324.      */   
  325.     public   static   int  DJBHash(String str)  
  326.     {  
  327.        int  hash =  5381 ;  
  328.   
  329.        for ( int  i =  0 ; i < str.length(); i++)  
  330.        {  
  331.           hash = ((hash << 5 ) + hash) + str.charAt(i);  
  332.        }  
  333.   
  334.        return  (hash &  0x7FFFFFFF );  
  335.     }  
  336.     /* End Of DJB Hash Function */   
  337.   
  338.     /**  
  339.      * DEK算法  
  340.      */   
  341.     public   static   int  DEKHash(String str)  
  342.     {  
  343.         int  hash = str.length();  
  344.   
  345.        for ( int  i =  0 ; i < str.length(); i++)  
  346.        {  
  347.           hash = ((hash << 5 ) ^ (hash >>  27 )) ^ str.charAt(i);  
  348.        }  
  349.   
  350.        return  (hash &  0x7FFFFFFF );  
  351.     }  
  352.     /* End Of DEK Hash Function */   
  353.   
  354.     /**  
  355.      * AP算法  
  356.      */   
  357.     public   static   int  APHash(String str)  
  358.     {  
  359.         int  hash =  0 ;  
  360.   
  361.        for ( int  i =  0 ; i < str.length(); i++)  
  362.        {  
  363.           hash ^= ((i & 1 ) ==  0 ) ? ( (hash <<  7 ) ^ str.charAt(i) ^ (hash >>  3 )) :  
  364.                                    (~((hash << 11 ) ^ str.charAt(i) ^ (hash >>  5 )));  
  365.        }  
  366.   
  367. //       return (hash & 0x7FFFFFFF);   
  368.        return  hash;  
  369.     }  
  370.     /* End Of AP Hash Function */   
  371.       
  372.     /**  
  373.      * JAVA自己带的算法  
  374.      */   
  375.     public   static   int  java(String str)  
  376. {  
  377.    int  h =  0 ;  
  378.    int  off =  0 ;  
  379.    int  len = str.length();  
  380.    for  ( int  i =  0 ; i < len; i++)  
  381.    {  
  382.     h = 31  * h + str.charAt(off++);  
  383.    }  
  384.    return  h;  
  385. }  
  386.       
  387.     /**  
  388.      * 混合hash算法,输出64位的值  
  389.      */   
  390.     public   static   long  mixHash(String str)  
  391.     {  
  392.     long  hash = str.hashCode();  
  393.     hash <<= 32 ;  
  394.     hash |= FNVHash1(str);  
  395.     return  hash;  
  396.     } 
一致性哈希算法是一种分布式算法,用于将数据分布到多个服务器节点,同时具有较好的负载均衡和容错性。下面是一致性哈希算法Java实现: ```java import java.util.SortedMap; import java.util.TreeMap; public class ConsistentHashing<T> { private final HashFunction hashFunction; private final int numberOfReplicas; private final SortedMap<Integer, T> circle = new TreeMap<>(); public ConsistentHashing(HashFunction hashFunction, int numberOfReplicas, Iterable<T> nodes) { this.hashFunction = hashFunction; this.numberOfReplicas = numberOfReplicas; for (T node : nodes) { add(node); } } public void add(T node) { for (int i = 0; i < numberOfReplicas; i++) { int hash = hashFunction.hash(node.toString() + i); circle.put(hash, node); } } public void remove(T node) { for (int i = 0; i < numberOfReplicas; i++) { int hash = hashFunction.hash(node.toString() + i); circle.remove(hash); } } public T get(Object key) { if (circle.isEmpty()) { return null; } int hash = hashFunction.hash(key); if (!circle.containsKey(hash)) { SortedMap<Integer, T> tailMap = circle.tailMap(hash); hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey(); } return circle.get(hash); } } ``` 这里的关键在于实现一个哈希函数HashFunction,可以使用Java中的MessageDigest类实现SHA-1哈希算法。具体实现可以参考以下代码: ```java import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class HashFunction { private final MessageDigest digest; public HashFunction() throws NoSuchAlgorithmException { this.digest = MessageDigest.getInstance("SHA-1"); } public int hash(Object key) { digest.reset(); byte[] bytes = digest.digest(key.toString().getBytes()); int result = 0; for (int i = 0; i < 4; i++) { result <<= 8; result |= (bytes[i] & 0xFF); } return result; } } ``` 使用示例: ```java import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) throws NoSuchAlgorithmException { HashFunction hashFunction = new HashFunction(); ConsistentHashing<String> consistentHashing = new ConsistentHashing<>(hashFunction, 3, Arrays.asList("server1", "server2", "server3")); System.out.println("Key \"test\" is assigned to server: " + consistentHashing.get("test")); System.out.println("Key \"test2\" is assigned to server: " + consistentHashing.get("test2")); consistentHashing.remove("server1"); System.out.println("After removing server1, key \"test\" is assigned to server: " + consistentHashing.get("test")); } } ``` 这个例子中,我们使用了3个虚拟节点来表示每个实际节点,当有新的节点加入到集群中时,会将其对应的虚拟节点分布到哈希环上。当查询某个键值时,会根据哈希值在哈希环上查找对应的节点。如果某个节点离开了集群,它对应的所有虚拟节点也会被移除。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值