2009年8月18日 星期二

Java HashMap VS C# Dictionary



Java Code:

HashMap< String , String > hm = new HashMap< String , String >();
hm.put("A", "A--Content");
hm.put("B", "B--Content");
//Get all value
for(Iterator< String > it = hm.keySet().iterator(); it.hasNext();){
String key = it.next();
System.out.println("Key: "+ key + ", value: "+hm.get(key));
}
//Get specific value
System.out.println(hm.get("A"));


C# Code:

Dictionary< string , string > dict = new Dictionary< string , string >();
try
{
dict.Add("A", "A--Content");
dict.Add("B", "B--Content");
//Get all value
foreach (KeyValuePair< string , string > kvp in dict)
{
Console.WriteLine("key: {0}, value: {1}", kvp.Key, kvp.Value);
}
//Get specific value
string val = "";
dict.TryGetValue("A", out val);
Console.WriteLine("value="+val);
//or
Console.WriteLine("value=" + dict["A"]);
}
catch (Exception)
{
//The method "Add" will throw exception if key already existed!!!
Console.WriteLine("Can't insert same key");
}

沒有留言: