zoukankan      html  css  js  c++  java
  • Hashtable的实现原理

    从狭义上来看, Hashtable 可以是一种具体类型名称:System.Collections.Hashtable ,从广义上来看, 它指的是一种数据结构, 即哈希表, 牵涉了多种具体类型, 像 HashMap, Dictionary 等等, 都属于哈希表的范畴。hashtable的具体类型为System.Collections.DictionaryEntry

    打开反编译器,Hashtable通过一个结构体bucket来表示其中的单个元素

    private struct bucket
    {
        public object key;
        public object val;
        public int hash_coll;
    }

    Key:键

    Val:Key所对应的值

    hash_coll:key所对应的哈希码

    uint num3 = this.InitHash(key, this.buckets.Length,out num ,out num2);

    这个num3 即hash_coll值

    hashtable中Add方法排序并非随意排序

    public virtual void Add(object key,object value)
    {
        this.Insert(key,value,true)
    }

    打开insert

    uint num3 = this.InitHash(key, this.buckets.Length,out num ,out num2);
    int num4 = 0;
    int index = -1;
    int num 6 = (int)(num %this.buckets.Length);

    num3即为hash_coll值

    num6则是存储数组数据的位置

    this.buckets[num6].val = nvalue;
    this.buckets[num6].key = key;
    this.buckets[num6].hash_coll|=(int) num3;

    是通过num对当前数组的长度来求余,确定数据存放的位置。hashtable的数据存储在buket数组中,这个数组需要存储三个值。通过key计算出一个hashcode值,用这个值与当前数组的长度做求余运算,得出一个索引下标,将数据存储到这个下标位置。

    取值的时候不需要通过遍历,儿是直接通过对象中存储hash_coll值计算出下表,显著提高效率。

    一个变量分配地址通过对象当前的hash_code来分配

    而在InitHash中有这样一句

    uint num = (uint)(this.GetHash(key)& 0x7fffffff);
    

     系统通过优化,尽可能找到不是重复的值,不同的数据在算完之后值可能是一样的,通过key值来运算,返回num值。

    num2:返回一个增加的值,降低重复的可能性。

  • 相关阅读:
    grunt in webstorm
    10+ Best Responsive HTML5 AngularJS Templates
    响应式布局
    responsive grid
    responsive layout
    js event bubble and capturing
    Understanding Service Types
    To add private variable to this Javascript literal object
    Centering HTML elements larger than their parents
    java5 新特性
  • 原文地址:https://www.cnblogs.com/longtime/p/3764297.html
Copyright © 2011-2022 走看看