.NET总结--泛型与泛型集合,应用场景

泛型优点

  1.提高代码复用性,代码简洁直观

  2.直接存储数据类型免去数据类型之间得隐式转换

  3.免去拆箱装箱过程,提高效率

  4.数据类型安全,存储时会验证是否对应该类型

泛型集合

  一. ArrayList与Array与List<T>

  1.ArrayList属于自增容器,也就是无需定义其长度可直接使用而Array需要定义其长度

  2.ArrayList包含操作某范围元素方法而Array只能获取一个或设置一个元素得值

  3.ArrayList可以轻松创建同步版本,而Array需要手动更新

  4.ArrayList需引用System.Collections方可使用而Array只需System即可

  5.已知特定类型(Object除外)Array要比ArrayList好用

  6.ArrayList与List<T>类型相似,但后者类型更加安全而且无需拆装箱操作便可直接使用

  7.ArrayList没有类型约束而List<T>需要约束类型

  

ArrayList arrayList1 = new ArrayList();
             arrayList1.
             arrayList1.Add("a");
             arrayList1.Add(1);
             arrayList1.Add("b");
             Response.Write(arrayList1[1]);

  

List < Student > students = new List < Student > ();
   Student stu1 = new Student();
   stu1.Name = "陆小凤";
   stu1.Number = "0801";
   stu1.Score = 20;
   Student stu2 = new Student();
   stu2.Name = "西门吹雪";
   stu2.Number = "0802";
   stu2.Score = 23;
   students.Add(stu1);
   students.Add(stu2);
   Console.WriteLine("集合中的元素个数为{0}", students.Count);
   foreach (Student stu in students)
   {
    Console.WriteLine("/t{0}/t{1}/t{2}", stu.Name, stu.Number, stu.Score);
   }
   students.Remove(stu1);
   Console.WriteLine("集合中的元素个数为{0}", students.Count);
   Console.ReadLine();

  

  二.  HashTable 与 Dictionary<key,value>类型

  1.单线程程序推荐Dictionary,读写速度快,容量利用更加便利

  2.多线程程序推荐HashTable,可以单线程写入,多线程读取

  3.Dictionary非线程安全,所以在使用时需要lock一下保护当前语句执行完成,而且二者都实现IDictionary接口,所以他们一般都是键值对

  4.Dictionary为按序插入数据队列若其中节点被删除后 顺序会被打乱

  5.HashTable 元素属于 Object类型所以在操作时经常发生装箱拆箱操作效率低于Dictionary

  深入解析:

    HashTable

    1.其本质是键值对形式存储,还有一个类似索引的值由HashCode的值类似索引值作为该数据位置索引

    2.GetHashCode可以获得尽量不会重复的值来作为该数据存储地址.这就是散列函数GetHashCode的作用

    3.当HashTable呗占用大半的时候GetHashCode可能会得到重复地址,这就是哈希冲突

    4.键值对在HashTable中的位置是由Position = (HashCode&0X7FFFFFFF)%HashTable.Length 来确定的

    5..NET中是用探测方法来解决哈希冲突的,当Position+x如果存在则位移至Position+2*x位置,所以HashTable占用越多计算时间越长存储速度越慢

    6.HashTable中当达到当前空间72%时会出现自动扩容,例如空间大小是100当位置占用到73的时候该空间会自动扩容

    Dictionary

    1.Dictionary是一种变种的HashTable主要是解决哈希冲突方式不同

  三. 功能对比

    测试代码属于摘抄:

    

public class HashTableTest

    {

        static Hashtable _Hashtable;

        static Dictionary<string, object> _Dictionary;

        static void Main()

        {

            Compare(10);

            Compare(10000);

            Compare(5000000);

            Console.ReadLine();

        }

        public static void Compare(int dataCount)

        {

            Console.WriteLine("-------------------------------------------------
");

            _Hashtable = new Hashtable();

            _Dictionary = new Dictionary<string, object>();

            Stopwatch stopWatch = new Stopwatch();

            //HashTable插入dataCount条数据需要时间

            stopWatch.Start();

            for (int i = 0; i < dataCount; i++)

            {

                _Hashtable.Add("Str" + i.ToString(), "Value");

            }

            stopWatch.Stop();

            Console.WriteLine(" HashTable插入" + dataCount + "条数据需要时间:" + stopWatch.Elapsed);

   

            //Dictionary插入dataCount条数据需要时间

            stopWatch.Reset();

            stopWatch.Start();

            for (int i = 0; i < dataCount; i++)

            {

                _Dictionary.Add("Str" + i.ToString(), "Value");

            }

            stopWatch.Stop();

            Console.WriteLine(" Dictionary插入" + dataCount + "条数据需要时间:" + stopWatch.Elapsed);

   

            //Dictionary插入dataCount条数据需要时间

            stopWatch.Reset();

            int si = 0;

            stopWatch.Start();

            for(int i=0;i<_Hashtable.Count;i++)

            {

                si++;

            }

            stopWatch.Stop();

            Console.WriteLine(" HashTable遍历时间:" + stopWatch.Elapsed + " ,遍历采用for方式");

   

            //Dictionary插入dataCount条数据需要时间

            stopWatch.Reset();

            si = 0;

            stopWatch.Start();

            foreach (var s in _Hashtable)

            {

                si++;

            }

            stopWatch.Stop();

            Console.WriteLine(" HashTable遍历时间:" + stopWatch.Elapsed + " ,遍历采用foreach方式");

   

            //Dictionary插入dataCount条数据需要时间

            stopWatch.Reset();

            si = 0;

            stopWatch.Start();

            IDictionaryEnumerator _hashEnum = _Hashtable.GetEnumerator();

            while (_hashEnum.MoveNext())

            {

                si++;

            }

            stopWatch.Stop();

            Console.WriteLine(" HashTable遍历时间:" + stopWatch.Elapsed + " ,遍历采用HashTable.GetEnumerator()方式");

   

            //Dictionary插入dataCount条数据需要时间

            stopWatch.Reset();

            si = 0;

            stopWatch.Start();

            for(int i=0;i<_Dictionary.Count;i++)

            {

                si++;

            }

            stopWatch.Stop();

            Console.WriteLine(" Dictionary遍历时间:" + stopWatch.Elapsed + " ,遍历采用for方式");

   

            //Dictionary插入dataCount条数据需要时间

            stopWatch.Reset();

            si = 0;

            stopWatch.Start();

            foreach (var s in _Dictionary)

            {

                si++;

            }

            stopWatch.Stop();

            Console.WriteLine(" Dictionary遍历时间:" + stopWatch.Elapsed + " ,遍历采用foreach方式");

   

            //Dictionary插入dataCount条数据需要时间

            stopWatch.Reset();

            si = 0;

            stopWatch.Start();

            _hashEnum = _Dictionary.GetEnumerator();

            while (_hashEnum.MoveNext())

            {

                si++;

            }

            stopWatch.Stop();

            Console.WriteLine(" Dictionary遍历时间:" + stopWatch.Elapsed + " ,遍历采用Dictionary.GetEnumerator()方式");

   

   

            Console.WriteLine("
-------------------------------------------------");

        }

    }

    综上测试可知:

    1.大量数据拆入时HashTable要比Dictionary慢很多

    2.for方式遍历HashTable和Dictionary速度最快

    3.foreach便利Dictionary时候花费时间更短

  三.  Queue和Stack

  1.Queue与Stack区别在于前者存储于队列,后者存储在栈中

  2.Queue属于先进先出,Stack属于先进后出 注意堆栈关系

  四.  SortedList

  1.引用System.Collections.SortList命名空间,其内部存储相当于两个数组 键数组与值数组 二者相关联关系,其中可以通过键来查询值,也可以根据值来搜索键,但是键不能为空,而值可以

  2.属于自增集合,可以根据自身数据大小来增加占用空间,也可以通过属性设置来减少空间

  3.若集合不再新增数据可以通过方法来设置该集合占用大小,注意该集合不会自动减少占用空间

  4.若输入键未存储则默认新增该键对应值数据,若该键对应值已有数据则默认覆盖原数据

  5.若不确定该键是否存在可以根据方法返回值判定是否存在

  泛型集合SortedList<key,value>例子:

  

static void Main(string[] args)  
06.        {  
07.            // 创建一个SortedList对象          
08.            SortedList mySortedList = new SortedList();  
09.            mySortedList.Add("First", "Hello");  
10.            mySortedList.Add("Second", "World");  
11.            mySortedList.Add("Third", "!");  
12.            mySortedList.Add("Four", "{1}quot;);    
13.  
14.            //列举SortedList的属性、键、值  
15.            Console.WriteLine("MySortedList");  
16.            Console.WriteLine("  Count:    {0}", mySortedList.Count);  
17.            Console.WriteLine("  Capacity: {0}", mySortedList.Capacity);  
18.            Console.WriteLine("  Keys and Values:");  
19.            PrintIndexAndKeysAndValues(mySortedList);  
20. 
21.            #region SortedList获得键、值列表  
22.            SortedList mySortedList1 = new SortedList();  
23.            mySortedList1.Add(1.3, "fox");  
24.            mySortedList1.Add(1.4, "jumped");  
25.            mySortedList1.Add(1.5, "over");  
26.            mySortedList1.Add(1.2, "brown");  
27.            mySortedList1.Add(1.1, "quick");  
28.            mySortedList1.Add(1.0, "The");  
29.            mySortedList1.Add(1.6, "the");  
30.            mySortedList1.Add(1.8, "dog");  
31.            mySortedList1.Add(1.7, "lazy");   
32.  
33.            //获得指定索引处的键和值  
34.            int myIndex = 3;  
35.            //     获取 System.Collections.SortedList 对象的指定索引处的键  
36.            Console.WriteLine("The key  at index {0} is {1}.", myIndex, mySortedList1.GetKey(myIndex));  
37.            //     获取 System.Collections.SortedList 对象的指定索引处的值  
38.            Console.WriteLine("The value at index {0} is {1}.", myIndex, mySortedList1.GetByIndex(myIndex));     
39.  
40.            // 获得SortedList中的键列表和值列表         
41.            IList myKeyList = mySortedList1.GetKeyList();  
42.            IList myValueList = mySortedList1.GetValueList();  
43.            // Prints the keys in the first column and the values in the second column.             
44.            Console.WriteLine("	-KEY-	-VALUE-");  
45.            for (int i = 0; i < mySortedList1.Count; i++)   
46.                Console.WriteLine("	{0}	{1}", myKeyList[i], myValueList[i]);  
47. 
48.            #endregion   
49. 
50.            #region 为SortedList中的元素重新赋值   
51.            // Creates and initializes a new SortedList.     
52.            SortedList mySortedList2 = new SortedList();  
53.            mySortedList2.Add(2, "two");  
54.            mySortedList2.Add(3, "three");   
55.            mySortedList2.Add(1, "one");  
56.            mySortedList2.Add(0, "zero");  
57.            mySortedList2.Add(4, "four");             
58.            // 打印显示列表的键和值           
59.            Console.WriteLine("The SortedList contains the following values:");  
60.            PrintIndexAndKeysAndValues(mySortedList2);        
61.     
62.            // 获得指定键的索引          
63.            int myKey = 2;  
64.            Console.WriteLine("The key "{0}" is at index {1}.", myKey, mySortedList2.IndexOfKey(myKey));        
65.            // 获得指定值的索引       
66.            String myValue = "three";  
67.            Console.WriteLine("The value "{0}" is at index {1}.", myValue, mySortedList2.IndexOfValue(myValue));        
68.            // 重新设置指定索引处的值           
69.            mySortedList2.SetByIndex(3, "III");   // SetByIndex:替换 System.Collections.SortedList 对象中指定索引处的值  
70.            mySortedList2.SetByIndex(4, "IV");         
71.            //打印显示列表的键和值         
72.            Console.WriteLine("After replacing the value at index 3 and index 4,");  
73.            PrintIndexAndKeysAndValues(mySortedList2);        
74.            #endregion  
75.            Console.ReadKey();  
76.        }  
77.  
78.        //打印SortedList中的键和值   
79.        public static void PrintIndexAndKeysAndValues(SortedList myList)    
80.        {              
81.            Console.WriteLine("	-INDEX-	-KEY-	-VALUE-");  
82.            for (int i = 0; i < myList.Count; i++)       
83.            {             
84.                Console.WriteLine("	[{0}]:	{1}	{2}", i, myList.GetKey(i), myList.GetByIndex(i));       
85.            }         
86.            Console.WriteLine();       
87.        }  
88.    }
static void Main(string[] args)  
06.        {  
07.            // 创建一个SortedList对象          
08.            SortedList mySortedList = new SortedList();  
09.            mySortedList.Add("First", "Hello");  
10.            mySortedList.Add("Second", "World");  
11.            mySortedList.Add("Third", "!");  
12.            mySortedList.Add("Four", "{1}quot;);    
13.  
14.            //列举SortedList的属性、键、值  
15.            Console.WriteLine("MySortedList");  
16.            Console.WriteLine("  Count:    {0}", mySortedList.Count);  
17.            Console.WriteLine("  Capacity: {0}", mySortedList.Capacity);  
18.            Console.WriteLine("  Keys and Values:");  
19.            PrintIndexAndKeysAndValues(mySortedList);  
20. 
21.            #region SortedList获得键、值列表  
22.            SortedList mySortedList1 = new SortedList();  
23.            mySortedList1.Add(1.3, "fox");  
24.            mySortedList1.Add(1.4, "jumped");  
25.            mySortedList1.Add(1.5, "over");  
26.            mySortedList1.Add(1.2, "brown");  
27.            mySortedList1.Add(1.1, "quick");  
28.            mySortedList1.Add(1.0, "The");  
29.            mySortedList1.Add(1.6, "the");  
30.            mySortedList1.Add(1.8, "dog");  
31.            mySortedList1.Add(1.7, "lazy");   
32.  
33.            //获得指定索引处的键和值  
34.            int myIndex = 3;  
35.            //     获取 System.Collections.SortedList 对象的指定索引处的键  
36.            Console.WriteLine("The key  at index {0} is {1}.", myIndex, mySortedList1.GetKey(myIndex));  
37.            //     获取 System.Collections.SortedList 对象的指定索引处的值  
38.            Console.WriteLine("The value at index {0} is {1}.", myIndex, mySortedList1.GetByIndex(myIndex));     
39.  
40.            // 获得SortedList中的键列表和值列表         
41.            IList myKeyList = mySortedList1.GetKeyList();  
42.            IList myValueList = mySortedList1.GetValueList();  
43.            // Prints the keys in the first column and the values in the second column.             
44.            Console.WriteLine("	-KEY-	-VALUE-");  
45.            for (int i = 0; i < mySortedList1.Count; i++)   
46.                Console.WriteLine("	{0}	{1}", myKeyList[i], myValueList[i]);  
47. 
48.            #endregion   
49. 
50.            #region 为SortedList中的元素重新赋值   
51.            // Creates and initializes a new SortedList.     
52.            SortedList mySortedList2 = new SortedList();  
53.            mySortedList2.Add(2, "two");  
54.            mySortedList2.Add(3, "three");   
55.            mySortedList2.Add(1, "one");  
56.            mySortedList2.Add(0, "zero");  
57.            mySortedList2.Add(4, "four");             
58.            // 打印显示列表的键和值           
59.            Console.WriteLine("The SortedList contains the following values:");  
60.            PrintIndexAndKeysAndValues(mySortedList2);        
61.     
62.            // 获得指定键的索引          
63.            int myKey = 2;  
64.            Console.WriteLine("The key "{0}" is at index {1}.", myKey, mySortedList2.IndexOfKey(myKey));        
65.            // 获得指定值的索引       
66.            String myValue = "three";  
67.            Console.WriteLine("The value "{0}" is at index {1}.", myValue, mySortedList2.IndexOfValue(myValue));        
68.            // 重新设置指定索引处的值           
69.            mySortedList2.SetByIndex(3, "III");   // SetByIndex:替换 System.Collections.SortedList 对象中指定索引处的值  
70.            mySortedList2.SetByIndex(4, "IV");         
71.            //打印显示列表的键和值         
72.            Console.WriteLine("After replacing the value at index 3 and index 4,");  
73.            PrintIndexAndKeysAndValues(mySortedList2);        
74.            #endregion  
75.            Console.ReadKey();  
76.        }  
77.  
78.        //打印SortedList中的键和值   
79.        public static void PrintIndexAndKeysAndValues(SortedList myList)    
80.        {              
81.            Console.WriteLine("	-INDEX-	-KEY-	-VALUE-");  
82.            for (int i = 0; i < myList.Count; i++)       
83.            {             
84.                Console.WriteLine("	[{0}]:	{1}	{2}", i, myList.GetKey(i), myList.GetByIndex(i));       
85.            }         
86.            Console.WriteLine();       
87.        }  
88.    }
原文地址:https://www.cnblogs.com/workstation-liunianguowang/p/9034172.html