.NET 没有hashmap,hashmap是Java容器;
There are several differences between HashMap and Hashtable in Java:
-
Hashtable
is synchronized, whereasHashMap
is not. This makesHashMap
better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. -
Hashtable
does not allownull
keys or values.HashMap
allows onenull
key and any number ofnull
values. -
One of HashMap's subclasses is
LinkedHashMap
, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out theHashMap
for aLinkedHashMap
. This wouldn't be as easy if you were usingHashtable
.
Since synchronization is not an issue for you, I'd recommend HashMap
. If synchronization becomes an issue, you may also look at ConcurrentHashMap
https://stackoverflow.com/questions/40471/differences-between-hashmap-and-hashtable
//dictionary
Dictionary<byte, string> mdic = new Dictionary<byte, string>();
mdic.Add(1, "Yaodada");
mdic.Add(2, "Meiei");
mdic.Add(3, "DFdsff");
foreach(KeyValuePair<byte,string> kvp in mdic)
{
Console.Write("key={0},value={1}", kvp.Key, kvp.Value);
}
Console.WriteLine("\n");
Console.Write("consoleWrite:"+mdic[1]+"\n");
string name;
if (mdic.TryGetValue(2, out name)) {
Console.Write(name+"\n");
}else
{
Console.Write("key not found..."+"\n");
}
//hashset
string[] array = new string[] { "AA", "BB", "CC", "DD", "CC", "BB" };
HashSet<string> mhash1 = new HashSet<string>(array);
Console.Write("mhash1: "+mhash1.Count+"\n");
foreach(string s in mhash1) {
Console.Write(s);
}
Console.Write("------------------------------------"+"\n");
string[] array2 = new string[] { "QQ", "WW", "EE", "FF", "GG" };
HashSet<string> mhash2 = new HashSet<string>(array2);
Console.Write("mhash2: " + mhash2.Count + "\n");
foreach (string s in mhash2)
{
Console.Write(s);
}
Console.Write("------------------------------------" + "\n");
mhash1.UnionWith(mhash2);
Console.Write("new mhash1: " + mhash1.Count + "\n");
foreach (string s in mhash1)
{
Console.Write(s+"\n");
}
//hashtable
Hashtable mtable = new Hashtable();
mtable.Add(1, "I");
mtable.Add(2, "See");
mtable.Add(3, "you");
foreach(DictionaryEntry d in mtable)
{
Console.Write("key={0},value={1};\n", d.Key, d.Value);
}
Console.ReadKey();