Hashtable和Dictionary<T,K>的內(nèi)部排序算法不一樣,請(qǐng)看代碼
Dictionary<string,string> ht=new Dictionary<string, string>(); ht.Add("http://www.sina.com.cn",""); ht.Add("http://www.bjut.edu.cn",""); ht.Add("http://lib.bjut.edu.cn", ""); ht.Add("http://news.bjut.edu.cn", ""); ht.Add("http://sse.bjut.edu.cn", ""); ht.Add("http://lexus.cnblogs.com", ""); ht.Add("http://www.sina.com.cn/sport", ""); ht.Add("http://www.sina.com.cn/ent", ""); foreach(var kvp in ht) Console.WriteLine(kvp.Key); Console.WriteLine("============================================"); Hashtable ht2=new Hashtable(); ht2.Add("http://www.sina.com.cn", ""); ht2.Add("http://www.bjut.edu.cn", ""); ht2.Add("http://lib.bjut.edu.cn", ""); ht2.Add("http://news.bjut.edu.cn", ""); ht2.Add("http://sse.bjut.edu.cn", ""); ht2.Add("http://lexus.cnblogs.com", ""); ht2.Add("http://www.sina.com.cn/sport", ""); ht2.Add("http://www.sina.com.cn/ent", ""); foreach(DictionaryEntry i in ht2) Console.WriteLine(i.Key);
兩組實(shí)現(xiàn)的代碼一樣,但是輸出的排序結(jié)果不一樣,這是為什么,我覺得Hashtable的排序應(yīng)該是比較正常的,大家覺得呢?
3 回答

慕運(yùn)維8079593
TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超5個(gè)贊
Dictionary默認(rèn)沒有排序的意思是它將按你Add的順序來(lái)存放,本身不會(huì)做排序操作
Hashtable的排序是根據(jù)Key的HashCode來(lái)進(jìn)行的,HashCode來(lái)自于Key的GetHashCode方法,一般值類型都直接使用系統(tǒng)已經(jīng)實(shí)現(xiàn)的GetHashCode方法,但引用類型多數(shù)情況下建議重寫GetHashCode()
- 3 回答
- 0 關(guān)注
- 531 瀏覽
添加回答
舉報(bào)
0/150
提交
取消