天天看点

getHashCode() 获取一致hash的简单算法

其中java的实现方式

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;
    }
 hash的定义:
 /** Cache the hash code for the string */
    private int hash; // Default to 0

/** The value is used for character storage. */
    private final char value[];

从上面的方法中可以看出hashCode的实现方法是:定义一个整形变量h,h的取值跟value字符数组的值有关,hashCode取值:((31*h+ASCII码字符)*31+第二个字符的ASCII码字符)*31+第三个字符的ASCII码字符
 
           

C#的实现方式

/// <summary>
    /// 哈希值处理
    /// 简单hash实现
    /// 每个字符的 char 值 +当前 index值,来确定这个hash值是唯一的
    /// </summary>
    public class HashCodeHelper
    {
        /// <summary>
        /// 每位位置所占的权值
        /// </summary>
        private static int Pow = 3;
        /// <summary>
        /// 返回此实例的哈希代码。
        /// </summary>
        /// <returns></returns>
        public static int GetHashCode(string key)
        {
            return HashCodeProcess(key);
        }
        /// <summary>
        /// hash数值处理
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private static int HashCodeProcess(string key)
        {
            int hashCode = 0;
            if (key != null && key.Length > 0)
            {
                hashCode = 0;
                for (int i = 0; i < key.Length; i++)
                {
                    hashCode = hashCode * Pow + key[i];
                }
            }
            return hashCode;
        }
    }