zoukankan      html  css  js  c++  java
  • C# GetHashCode 的实现方式


    在项目中,在使用哈希表时。有时会须要Override GetHashCode。

    这里给出一种普遍的做法:


    版本号1:
    实现一个helper。传递类型T。返回这个类型的hashcode。函数逻辑非常直接,仅仅是做了null check而已。假设obj不为空,则直接使用obj的hash code。


    public class HashHelper
    {
    	private int _seed = 17;	
    	public int Hash<T>(T obj)
    	{
    		// why 31?

    // https://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/ // shortly, to reduce the conflict of hashing key's distrabution return 31 * _seed + ((obj == null) ?

    -1 : obj.GetHashCode()); } }




    为什么使用了magic number 31? 使用素数乘积能够相对添加唯一性,降低哈希键值分配时的冲突;而31则是为了编译器优化的考虑(有效的转换为i<<5-1)。大概搜了一下,这样的实现方式来自JAVA中string 的hash code函数。这里有具体介绍:
    https://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/




    实现版本号2:
    能够扩展这个类成为流畅接口,它能够hash各种类型的。对于值类型来说,重载的意义在于降低装箱。对于集合或泛型,则为了让外部调用更自然。可读性更强。




    public class HashFluent
    {
    	private int _seed = 17;	
    	private int _hashContext;
    	
    	public HashFluent Hash<T>(T obj)
    	{
    		// why 31?
    		// https://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/
    		// shortly, to reduce the conflict of hashing key's distrabution
    		_hashContext = 31 * _seed + ((obj == null) ? -1 : obj.GetHashCode());
    		return this;
    	}
    	
    	public HashFluent Hash(int? value)
    	{
    		_hashContext = 31 * _seed + ((value == null) ? -1 : value.GetHashCode());
    		return this;
    	}
    	
    	public HashFluent Hash(IEnumerable sequence)
    	{
    		if (sequence == null)
    		{
    			_hashContext = 31 * _hashContext + -1;
    		}
    		else
    		{
    			foreach (var element in sequence)
    			{
    				_hashContext = 31 * _hashContext + ((element == null) ?

    -1 : element.GetHashCode()); } } return this; } public override int GetHashCode (){ return _hashContext; } // add more overridings here .. // add value types overridings to avoid boxing which is important }



  • 相关阅读:
    PyQt5-关闭窗体显示提示框(窗口界面显示器上居中)-5
    PyQt5-按钮关闭窗体-4
    PyQt5-显示提示消息文本-3
    PyQt5-显示一个窗体,设置标题和图标-2
    [bzoj1053][HAOI2007]反素数ant【暴力】
    [bzoj1083][SCOI2005]繁忙的都市【MST】
    [bzoj1088][SCOI2005]扫雷Mine【乱搞】
    [bzoj1070][SCOI2007]修车【费用流】
    [bzoj1087][SCOI2005]互不侵犯King【dp】
    [bzoj4558][JLoi2016]方【容斥原理】【计数】
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/6914337.html
Copyright © 2011-2022 走看看