作者:AmenTo_AT | 来源:互联网 | 2023-05-30 10:10
我贴出代码让大家上机测试:支持上机usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;u
我贴出代码让大家上机测试:支持上机
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 基本功修炼
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add("1", "张三");
ht.Add("2", "张四");
ht.Add("3", "王五");
ht.Add("4", "四");
ht.Add("5", "五");
foreach (var item in ht.Keys)
{
Console.WriteLine(item + " hashCode =" + item.GetHashCode());
}
foreach (var item in ht.Values)
{
Console.WriteLine(item);
}
}
}
}
我先上图
不知道大家发现了什么:我们输出的value是按照插入的顺序先后输出的,也就是那个先进先出,那么我在来改变下key的值在看图是不是还是一样呢
大家发现没输出顺序不对了,第一个不在是我们想像的张三。 我们在仔细观察上面那个-843…的数字,比下大小。
我们会发现这个hashCode值越大越最后输出,我们是不是想到了数组索引0,1,2越来越多,有没有发现像遍历数组。
没有错,其实hashTable存数据的时候是会把key,value以及通过key生成的hashCode存入一个结构做为一个整体。然后通过hashCode值作为数组索引把这个结构存入数组。
其实我们也发现了这个hashCode是根据key对应的公式计算的。具体怎么InitHashCode这个方法我们就细看,想看的话我建议你们通过反编译看iL中间代码。会比较详细。