談談Dictionary<T1,T2>和List<T>的問題

來源:互聯網
上載者:User

引子:

事情的起因我已經記不清了,但是事情的根本原因在於,我們要遍曆一個集合,是用字典來儲存還是用數組鏈表來儲存。

1.把基本概念說清

對List<T>的闡述,我在http://www.cnblogs.com/kym/archive/2009/03/09/1406657.html一文中已經有過相應的解釋,再此不再贅述。

Dictionary<T1,T2>,我們俗稱其為字典,他包含一個Key和與之對應的Value,其目的是能夠根據Key迅速地找到Value,演算法複雜度為O(1)。

2.Dictionary<T1,T2>和Hashtable的異同

首先很多人都認同一個觀點,說Dictionary<T1,T2>是HashTable的泛型版本,這一點在大致上是正確的,可是當我們運行這樣一段代碼時,便可看出他們的不同:

代碼

1             Dictionary<int, int> dic = new Dictionary<int, int>();
2             dic.Add(1, 5);
3             dic.Add(10, 3);
4             dic.Add(2, 5);
5             foreach (int key in dic.Keys)
6             {
7                 Console.WriteLine(key);
8             }
9
10             Hashtable hashtable = new Hashtable();
11             hashtable.Add(1, 5);
12             hashtable.Add(10, 3);
13             hashtable.Add(2, 5);
14             foreach (object key in hashtable.Keys)
15             {
16                 Console.WriteLine(key.ToString());
17             }

Dictionary<T1,T2>是根據插入的順序來遍曆,但是Hashtable在插入時會打亂其位置。

並且我們在用Reflector看源碼的時候也會發現

代碼

1 if ((this.buckets[num6].key == null) || ((this.buckets[num6].key == this.buckets) && ((this.buckets[num6].hash_coll & 0x80000000L) == 0L)))
2     {
3         if (index != -1)
4         {
5             num6 = index;
6         }
7         Thread.BeginCriticalRegion();
8         this.isWriterInProgress = true;
9         this.buckets[num6].val = nvalue;
10         this.buckets[num6].key = key;
11         this.buckets[num6].hash_coll |= (int) num3;
12         this.count++;
13         this.UpdateVersion();
14         this.isWriterInProgress = false;
15         Thread.EndCriticalRegion();
16     }
17

Hashtable是安全執行緒的,而Dictionary明顯不具備如此特性。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.