微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

HashTable Dictionary HashMap

HashTable和HashMap

脑海中一直存在两个Hash,一个是HashMap另一个是HashTable,今天来总结一下两者的区别

相同点:表示根据键的哈希代码进行组织的键/值对的集合,哈希表也叫散列表。

区别:HashMap在C#中不存在的,而是在Java中

1.C#每一个元素都是存储在DictionaryEntry对象中的键/值对,键不能为 null,但值可以。

2.在Java的HashMap中,null可以作为键,这样的键只有一个;可以有一个或多个键所对应的值为null。当get()方法返回null值时,即可以表示HashMap中没有该键,也可以表示该键所对应的值为null。

因此,在HashMap中不能由get()方法来判断HashMap中是否存在某个键,而应该用containsKey()方法来判断

HashTable示例

using System;
using System.Collections;
 
namespace MyCollection
{
    public class HashTableExample
    {
        static void Main()
        {
            // Create a new hash table.
            Hashtable openWith = new Hashtable();
 
            // key没有重复,但是value有重复.
            openWith.Add("txt","notepad.exe");
            openWith.Add("bmp",1)">"paint.exe");
            openWith.Add("dib",1)">"rtf",1)">"wordpad.exe");
 
            //如果key重复,进行catch处理
            try
            {
                openWith.Add("winword.exe");
            }
            catch
            {
                Console.WriteLine("An element with Key = \"txt\" already exists.");
            }
 
            // 通过key获取value
            Console.WriteLine("For key = \"rtf\",value = {0}.",openWith["rtf"]);
 
            //替换value
            openWith["rtf"] = "winword.exe";
            Console.WriteLine(//遍历HashTable
            foreach (DictionaryEntry de in openWith)
            {
                Console.WriteLine(de.Key);
            }
 
            //获取Keys
            ICollection keCollection = openWith.Keys;
            foreach (string s in keCollection)
            {
                Console.WriteLine("key = {0}",s);
            }
 
            //删除指定的key
            openWith.Remove("doc");
            if (!openWith.Contains("doc"))
            {
                Console.WriteLine("Key\"doc\" is not found");
            }
        }
    }
}

运行结果

image

HashTable和Dictionary

示例代码