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
{
public static void Main()
{
// Create a new hash table.
Hashtable openWith = new Hashtable();
// key沒有重復, 但是value有重復.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
//如果key重復,進行catch處理
try
{
openWith.Add("txt", "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("For key = \"rtf\", value = {0}.", openWith["rtf"]);
//遍歷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");
}
}
}
}
運行結果
HashTable和Dictionary
示例代碼
using System;
using System.Collections;
using System.Collections.Generic;
namespace MyCollection
{
class HashTableDictionary
{
static void Main(string[] args)
{
Hashtable hashtable = new Hashtable();
hashtable.Add("8","Name8");
hashtable.Add("2", "Name5");
hashtable.Add("5", "Name2");
hashtable.Add("1", "Name1");
foreach (var hash in hashtable.Keys)
{
Console.WriteLine(hash.ToString());
}
Console.WriteLine();
Dictionary<int,string> dict = new Dictionary<int, string>();
dict.Add(8, "Name8");
dict.Add(2, "Name5");
dict.Add(5, "Name2");
dict.Add(1, "Name1");
foreach (var _dict1 in dict.Keys)
{
Console.WriteLine(_dict1);
}
Console.WriteLine();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
dict2.Add("8", "Name8");
dict2.Add("2", "Name5");
dict2.Add("5", "Name2");
dict2.Add("1", "Name1");
foreach (var _dict2 in dict2.Keys)
{
Console.WriteLine(_dict2);
}
}
}
}
運行結果