集合框架 IList,IList——向量(1)

点击打开链接


向量是一个可以动态改变长度的数组,起作用就是无需确定集合的初始长度,集合会随着存放数据的数量自行变化。

.net Framwork中提供了两种向量的规范:

  • 集合元素类型为Object类型的IList接口,可以存放不同类型的对象引用;
  • 以泛型为基础的IList<T>接口,只能存放一种类型的对象引用。

下图展示了IList接口及IList<T>接口的继承层次


图1 IList及IList<T>继承层次图

一、IList接口

1.1 接口特点:

IList接口从ICollection接口继承,所以其具备如下特性:

  • 可获取集合元素个数 - Count属性;
  • 可迭代 - GetEnumerator方法(从IEnumerable接口继承);
  • 集合元素传递给数组 - CopyTo方法。

IList接口添加了如下特性:

  • 访问集合任意索引所在元素 - this[]索引器属性;
  • 向集合末尾添加元素 - Add方法;
  • 向集合特定位置插入元素 - Insert方法;
  • 删除特定元素 - Remove方法;
  • 删除索引位置特定的元素 - RemoveAt方法;
  • 判断对象是否在集合中被引用 - Contains方法;
  • 查找特定对象在集合中的索引位置 - IndexOf方法;
  • 清空整个集合 - Clear方法。

IList类型集合按照顺序存放元素(所谓顺序即IList类型集合不会改变元素的存放顺序)。

1.2 IList<T>接口 

IList<T>接口从ICollection<T>接口继承,所以其具备如下特性:

  • 可获取集合元素个数 - Count属性;
  • 可迭代 - GetEnumerator方法(从IEnumerable接口继承);
  • 集合元素传递给数组 - CopyTo方法;
  • 向集合末尾添加元素 - Add方法;
  • 删除特定元素 - Remove方法;
  • 判断对象是否在集合中被引用 - Contains方法;
  • 清空整个集合 - Clear方法。

IList<T>接口添加了如下特性:

  • 访问集合任意索引所在元素 - this[]索引器属性
  • 向集合特定位置插入元素 - Insert方法;
  • 删除索引位置特定的元素 - RemoveAt方法;
  • 查找特定对象在集合中的索引位置 - IndexOf方法;

IList<T>类型集合按照顺序存放特定类型元素

二、算法

另外,向量集合和数组一样,具备随机访问特点。即无论访问向量集合的任何一个单元,所需的访问时间是完全相同的。C#的IList/IList<T>接口表现出C++中vector<T>的特性。

  • 实际应用中,我们大多使用泛型向量,因为它更安全且高效。

在向量类中,依然使用普通数组来记录集合数据,只是向量使用了一些算法技巧,让整个类对外表现不同于普通数组的重要特点可以动态的改变数组长度,具体算法要点如下:

在内部数组长度足够的情况下,直接进行添加或插入操作(必要时需要数据搬移); 
在内部数组长度不足的情况下,按照内部数组长度加1的2倍作为新数组的长度分配新数组,进行必要数据搬移,进行添加或插入操作; 
在数据删除时,并不改变内部数组的长度,而仅仅是使用被删除数据之后的数据覆盖被删除数据即可。

向量再分配元素存储空间时,使用了典型的空间换时间原则,即每次空间不足的时候,都多分配一些冗余空间,以求最低限度的减少内存分配次数。内存分配是程序性能的一个瓶颈,应尽量避免集中的次数繁多的内存分配。

三、实现类

.net Framework提供了IList和IList<T>的实现类,它们是ArrayList类List<T>类,其中:

  • ArrayList类处于System.Collections命名空间下;
  • List<T>类处于System.Collections.Specialized命名空间下。

四、一个IList接口的实现(源代码)

ArrayList.cs

[c-sharp]  view plain  copy
  1. using System;  
  2. using System.Collections;  
  3.    
  4. namespace Edu.Study.Collections.List {  
  5.    
  6.     /// <summary>  
  7.     /// 定义向量集合类, 实现IList接口  
  8.     /// </summary>  
  9.     public class ArrayList : IList {  
  10.    
  11.         /// <summary>  
  12.         /// 迭代子定义, 实现IEnumerator接口, 具备如下属性和方法:  
  13.         ///    - Current属性, object类型属性, 获取集合的“当前”位置元素;  
  14.         ///    - MoveNext方法, 移动到集合下一个元素, 返回是否移动到集合末尾的布尔值;  
  15.         ///    - Reset方法, 返回初始状态。  
  16.         /// </summary>  
  17.         public struct Enumertor : IEnumerator {  
  18.    
  19.             /// <summary>  
  20.             /// 表示迭代索引, 即迭代器访问到向量的下标  
  21.             /// </summary>  
  22.             private int index;  
  23.    
  24.             /// <summary>  
  25.             /// 一个到迭代器所属的向量类对象的引用  
  26.             /// </summary>  
  27.             private ArrayList list;  
  28.    
  29.             /// <summary>  
  30.             /// 参数构造器  
  31.             /// </summary>  
  32.             /// <param name="<a href="http://lib.csdn.net/base/docker" class='replace_word' title="Docker知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Container</a>">表示迭代器所属的集合类</param>  
  33.             public Enumertor(ArrayList container) {  
  34.                 this.list = container;  
  35.                 this.index = -1;  
  36.             }  
  37.    
  38.             /// <summary>  
  39.             /// 获取迭代器当前数据对象。  
  40.             /// 在向量中, 这个属性根据ArrayList.index字段的值, 返回向量对应位置的对象引用  
  41.             /// </summary>  
  42.             public object Current {  
  43.                 get {  
  44.                     return list[index];  
  45.                 }  
  46.             }  
  47.    
  48.             /// <summary>  
  49.             /// 将迭代器指示到“下一个数据位置”  
  50.             /// 在向量中, 这个方法将index字段的值加1(在这个值小于向量长度的前提下)  
  51.             /// </summary>  
  52.             /// <returns>当迭代器到达数据集合末尾时, 返回false</returns>  
  53.             public bool MoveNext() {  
  54.                 if (this.index < list.Count) {  
  55.                     ++this.index;  
  56.                 }  
  57.                 return this.index < list.Count;  
  58.             }  
  59.    
  60.             /// <summary>  
  61.             /// 将迭代器指示恢复到集合起始位置。  
  62.             /// 在向量中, 这个方法将index字段的恢复为-1  
  63.             /// </summary>  
  64.             public void Reset() {  
  65.                 this.index = -1;  
  66.             }  
  67.         }  
  68.    
  69.         /// <summary>  
  70.         /// 保存集合的数组  
  71.         /// </summary>  
  72.         private object[] array;  
  73.    
  74.         /// <summary>  
  75.         /// 当前集合的长度  
  76.         /// </summary>  
  77.         private int count;  
  78.    
  79.         /// <summary>  
  80.         /// 默认构造器  
  81.         /// </summary>  
  82.         public ArrayList()  
  83.             : this(1) {  
  84.         }  
  85.    
  86.         /// <summary>  
  87.         /// 参数构造器  
  88.         ///    提供这个参数构造器可以预先的初始化内部数组的长度, 减少内部数组重新分配  
  89.         /// 内存的次数, 提高效率。但参数设置过大则会浪费内存。  
  90.         /// </summary>  
  91.         /// <param name="capacity">初始化时内部数组的长度</param>  
  92.         public ArrayList(int capacity) {  
  93.             if (capacity < 0) {  
  94.                 throw new ArgumentOutOfRangeException("caption");  
  95.             }  
  96.    
  97.             if (capacity == 0) {  
  98.                 capacity = 1;  
  99.             }  
  100.             this.array = new object[capacity];  
  101.             this.count = 0;  
  102.         }  
  103.    
  104.         /// <summary>  
  105.         /// 获取向量的长度  
  106.         /// </summary>  
  107.         public int Count {  
  108.             get {  
  109.                 return this.count;  
  110.             }  
  111.         }  
  112.    
  113.         /// <summary>  
  114.         /// 返回向量实际使用的长度  
  115.         /// </summary>  
  116.         public int Capacity {  
  117.             get {  
  118.                 return this.array.Length;  
  119.             }  
  120.         }  
  121.    
  122.         /// <summary>  
  123.         /// 是否固定大小的属性(返回常量false)  
  124.         /// </summary>  
  125.         public bool IsFixedSize {  
  126.             get {  
  127.                 return false;  
  128.             }  
  129.         }  
  130.    
  131.         /// <summary>  
  132.         /// 是否只读集合的属性(返回常量false)  
  133.         /// </summary>  
  134.         public bool IsReadOnly {  
  135.             get {  
  136.                 return false;  
  137.             }  
  138.         }  
  139.    
  140.         /// <summary>  
  141.         /// 集合是否可同步属性, 返回false, 表示集合无法同步  
  142.         /// </summary>  
  143.         public bool IsSynchronized {  
  144.             get {  
  145.                 return false;  
  146.             }  
  147.         }  
  148.    
  149.         /// <summary>  
  150.         /// 同步对象属性, 返回null, 表示集合无需同步  
  151.         /// </summary>  
  152.         public object SyncRoot {  
  153.             get {  
  154.                 return null;  
  155.             }  
  156.         }  
  157.    
  158.         /// <summary>  
  159.         /// 当this.array长度不够时, 重新分配长度足够的新数组。  
  160.         /// 分配新数组的原则是:以原数组长度加 1 的 2 倍作为新数组的长度  
  161.         /// </summary>  
  162.         /// <returns>分配的新数组</returns>  
  163.         private object[] GetNewArray() {  
  164.             return new object[(this.array.Length + 1) * 2];  
  165.         }  
  166.    
  167.         /// <summary>  
  168.         /// 向向量的末尾添加对象。  
  169.         /// 在发生内部数组长度不足的情况下, 程序按照(原有数组长度 + 1) * 2的原则产生新数组  
  170.         /// </summary>  
  171.         /// <param name="value">要添加的对象</param>  
  172.         public int Add(object value) {  
  173.    
  174.             // 计算增加后集合长度  
  175.             int newCount = this.count + 1;  
  176.    
  177.             // 判断当前数组数量是否能满足要求  
  178.             if (this.array.Length < newCount) {     // 当数组长度不足  
  179.    
  180.                 // 分配新数组  
  181.                 object[] newArray = GetNewArray();  
  182.    
  183.                 // 将原数组的元素复制到新数组中  
  184.                 Array.Copy(this.array, newArray, this.count);  
  185.    
  186.                 // 重新设定内部数组字段的引用  
  187.                 this.array = newArray;  
  188.             }  
  189.    
  190.             // 添加新数据  
  191.             this.array[this.count] = value;  
  192.             this.count = newCount;  
  193.    
  194.             // 返回添加项的索引位置  
  195.             return this.count - 1;  
  196.         }  
  197.    
  198.         /// <summary>  
  199.         /// 索引器属性, 按索引返回向量中的某一项  
  200.         /// </summary>  
  201.         /// <param name="index">索引数</param>  
  202.         /// <returns>数组中第index项的对象引用</returns>  
  203.         public object this[int index] {  
  204.             get {  
  205.                 if (index < 0 || index >= this.count) {  
  206.                     throw new ArgumentOutOfRangeException("index");  
  207.                 }  
  208.                 return this.array[index];  
  209.             }  
  210.             set {  
  211.                 if (index < 0 || index >= this.count) {  
  212.                     throw new ArgumentOutOfRangeException("index");  
  213.                 }  
  214.                 this.array[index] = value;  
  215.             }  
  216.         }  
  217.    
  218.         /// <summary>  
  219.         /// 删除向量中的元素  
  220.         /// </summary>  
  221.         /// <param name="index">开始删除的起始索引</param>  
  222.         /// <param name="count">要删除的元素的个数</param>  
  223.         public void RemoveRange(int index, int count) {  
  224.             if (index < 0) {  
  225.                 throw new ArgumentOutOfRangeException("index");  
  226.             }  
  227.    
  228.             // 计算最后一个被删除元素的索引位置  
  229.             int removeIndex = index + count;  
  230.    
  231.             // 查看要删除的元素索引位置是否在合理范围内  
  232.             if (count < 0 || removeIndex > this.count) {  
  233.                 throw new ArgumentOutOfRangeException("count");  
  234.             }  
  235.    
  236.             // 将待删除元素其后的数据拷贝到待删除元素位置  
  237.             Array.Copy(this.array, index + 1, this.array, index + count - 1, this.count - removeIndex);  
  238.    
  239.             // 重新设定向量长度  
  240.             this.count -= count;  
  241.         }  
  242.    
  243.         /// <summary>  
  244.         /// 从集合中删除特定对象的引用  
  245.         /// </summary>  
  246.         /// <param name="value">要从集合中删除的对象引用</param>  
  247.         public void Remove(object value) {  
  248.    
  249.             // 查找value在数组中所在的索引位置  
  250.             int index = this.IndexOf(value);  
  251.    
  252.             // 如果找到了该元素所在的位置  
  253.             if (index >= 0) {  
  254.    
  255.                 // 删除索引位置处一个元素  
  256.                 this.RemoveRange(index, 1);  
  257.             }  
  258.         }  
  259.    
  260.         /// <summary>  
  261.         /// 从集合的特定位置删除对象的引用  
  262.         /// </summary>  
  263.         /// <param name="index">要删除对象引用所在的位置</param>  
  264.         public void RemoveAt(int index) {  
  265.    
  266.             // 删除索引处一个元素  
  267.             RemoveRange(index, 1);  
  268.         }  
  269.    
  270.    
  271.         /// <summary>  
  272.         /// 查找对应的数组项  
  273.         /// </summary>  
  274.         /// <param name="o">待查找的对象</param>  
  275.         /// <returns>被查到的对象所在的索引位置, -1表示没有找到</returns>  
  276.         /// <remarks>该方法使用了顺序查找的方法逐一比较数组中的元素进行查找</remarks>  
  277.         public int IndexOf(object value) {  
  278.    
  279.             // 注意, 这里面使用到了一个查询技巧, 以避免抛出异常  
  280.             // 由于数组中可以存在null值, 而参数value也可以为null, 所以查询比较要分为两种情况  
  281.             //    - 当参数value为null时, 只需要从数组中找到第一个同为null的数组项即可;  
  282.             //    - 当参数value为非null时, 则可以调用其Equals方法, 来逐一和数组项进行比较.   
  283.             // 一定要防止使用值为null的数组项或变量来调用任何属性或方法.  
  284.    
  285.             int index = 0;  
  286.             if (value == null) { // 处理参数为null的情况  
  287.                 while (index < this.count) {  
  288.                     if (this.array[index] == null) {  
  289.                         return index;  
  290.                     }  
  291.                     ++index;  
  292.                 }  
  293.             } else { // 处理参数为非null的情况  
  294.                 while (index < this.count) {  
  295.                     if (value.Equals(this.array[index])) {  
  296.                         return index;  
  297.                     }  
  298.                     ++index;  
  299.                 }  
  300.             }  
  301.    
  302.             // 未找到匹配项, 返回-1表示没找到  
  303.             return -1;  
  304.         }  
  305.    
  306.         /// <summary>  
  307.         /// 弹出向量的最后一个元素(即获取最后一个元素的引用后删除最后一个元素)  
  308.         /// </summary>  
  309.         /// <returns>数组的最后一个对象</returns>  
  310.         public object PopBack() {  
  311.             object o = this.array[this.count - 1];  
  312.             RemoveAt(this.count - 1);  
  313.             return o;  
  314.         }  
  315.    
  316.         /// <summary>  
  317.         /// 弹出向量的第一个对象  
  318.         /// </summary>  
  319.         /// <returns>数组的第一个对象</returns>  
  320.         public object PopFront() {  
  321.             object o = this.array[0];  
  322.             RemoveAt(0);  
  323.             return o;  
  324.         }  
  325.    
  326.         /// <summary>  
  327.         /// 向数组的任意地方插入数据  
  328.         /// </summary>  
  329.         /// <param name="index">要插入的位置</param>  
  330.         /// <param name="value">要插入的值</param>  
  331.         public void Insert(int index, object value) {  
  332.             if (index >= this.count) {  
  333.                 throw new ArgumentOutOfRangeException("index");  
  334.             }  
  335.    
  336.             // 插入数据采用和添加数据(Add方法)相同的算法.   
  337.             // 即array字段长度不足以容纳新插入数据时, 实例  
  338.             // 化一个新数组, 长度是array字段数组长度 + 1的  
  339.             // 2倍.  
  340.    
  341.             int newCount = this.count + 1;  
  342.    
  343.             // 插入的原则是, 将数组元素从插入位置起向后全部移动一个位置  
  344.             // 将待插入的对象引用存入空余出的位置中  
  345.              
  346.             if (this.array.Length < newCount) {    // array字段数组容量不足  
  347.                 object[] newArray = GetNewArray();  
  348.                 Array.Copy(this.array, newArray, index);  
  349.                 newArray[index] = value;  
  350.                 Array.Copy(this.array, index, newArray, index + 1, this.count - index);  
  351.                 this.array = newArray;  
  352.             } else { // array字段数组容量足够  
  353.                 Array.Copy(this.array, index, this.array, index + 1, this.count - index);  
  354.                 this.array[index] = value;  
  355.             }  
  356.             this.count = newCount;  
  357.         }  
  358.    
  359.         /// <summary>  
  360.         /// 查看当前向量是否包含制定对象  
  361.         /// </summary>  
  362.         /// <param name="value">要查找的对象</param>  
  363.         /// <returns>是否包含指定对象</returns>  
  364.         public bool Contains(object value) {  
  365.             return this.IndexOf(value) >= 0;  
  366.         }  
  367.    
  368.         /// <summary>  
  369.         /// 将内部数组的长度压缩为向量的实际长度  
  370.         /// </summary>  
  371.         public void TrimToSize() {  
  372.    
  373.             // 从Add方法和Insert方法可以看出, 向量在添加元素时, 会产生大量的冗余  
  374.             // 这个方法就是消除冗余的  
  375.    
  376.             // 判断是否产生了冗余(数组长度大于向量实际长度)  
  377.             if (this.array.Length > this.count) {  
  378.                 object[] newArray = null;  
  379.    
  380.                 // 实例化一个和向量实际长度相同的数组  
  381.                 // 将向量中的元素逐一存储到这个数组中  
  382.                 // 替换掉array字段保存的旧数组引用  
  383.    
  384.                 if (this.count > 0) {  
  385.                     newArray = new object[this.count];  
  386.                     Array.Copy(this.array, newArray, this.count);  
  387.                 } else {  
  388.                     newArray = new object[1];  
  389.                 }  
  390.                 this.array = newArray;  
  391.             }  
  392.         }  
  393.    
  394.         /// <summary>  
  395.         /// 清空向量  
  396.         /// </summary>  
  397.         public void Clear() {  
  398.    
  399.             // 无需重新分配空间, 将count字段设置为0即可  
  400.             this.count = 0;  
  401.         }  
  402.    
  403.         /// <summary>  
  404.         /// 获取该集合类的迭代器  
  405.         /// </summary>  
  406.         /// <returns>该集合类的迭代器</returns>  
  407.         public IEnumerator GetEnumerator() {  
  408.             Enumertor ator = new Enumertor(this);  
  409.             return ator;  
  410.         }  
  411.    
  412.         /// <summary>  
  413.         /// 将集合中的元素复制到数组中  
  414.         /// </summary>  
  415.         /// <param name="array"></param>  
  416.         /// <param name="index"></param>  
  417.         public void CopyTo(Array array, int index) {  
  418.             Array.Copy(this.array, 0, array, index, this.count);  
  419.         }  
  420.     }  
  421. }  

仔细观察上述代码,弄清楚两个问题:

  1. 迭代子类(17 - 67行)是如何实现的,其内部原理是什么?
  2. 向量是如何存储对象引用的,存储分配的算法(163 - 164行)是什么?

另外还要注意的索引器的使用(203行),利用索引器可以表现出来更优美的语法;

可以采用如下代码测试ArrayList类:

Program.cs

[c-sharp]  view plain  copy
  1. using System;  
  2.    
  3. namespace Edu.Study.Collections.List {  
  4.     class Program {  
  5.         static void Main(string[] args) {  
  6.    
  7.             // 声明向量集合对象  
  8.             ArrayList lst = new ArrayList();  
  9.    
  10.             // 添加两个元素  
  11.             lst.Add(10);  
  12.             lst.Add(20);  
  13.    
  14.             // 使用for循环和索引器遍历集合  
  15.             for (int i = 0; i < lst.Count; ++i) {  
  16.                 Console.WriteLine(lst[i]);  
  17.             }  
  18.             Console.WriteLine();  
  19.    
  20.             // 使用迭代循环遍历集合  
  21.             foreach (object o in lst) {  
  22.                 Console.WriteLine(o);  
  23.             }  
  24.             Console.WriteLine();  
  25.    
  26.             // 像第2个元素前插入新元素  
  27.             lst.Insert(1, 100);  
  28.             foreach (object o in lst) {  
  29.                 Console.WriteLine(o);  
  30.             }  
  31.             Console.WriteLine();  
  32.    
  33.             // 删除值为100的元素(此处测试值类型,童鞋们可以自行测试引用类型)  
  34.             lst.Remove(100);  
  35.             foreach (object o in lst) {  
  36.                 Console.WriteLine(o);  
  37.             }  
  38.             Console.WriteLine();  
  39.    
  40.             // 删除第2个元素  
  41.             lst.RemoveAt(1);  
  42.             foreach (object o in lst) {  
  43.                 Console.WriteLine(o);  
  44.             }  
  45.             Console.WriteLine();  
  46.    
  47.             // 清空集合  
  48.             lst.Clear();  
  49.             foreach (object o in lst) {  
  50.                 Console.WriteLine(o);  
  51.             }  
  52.             Console.WriteLine();  
  53.    
  54.             // 添加10个随机数  
  55.             Random rand = new Random();  
  56.             for (int i = 0; i < 10; ++i) {  
  57.                 lst.Add(rand.Next(10));  
  58.             }  
  59.             foreach (object o in lst) {  
  60.                 Console.WriteLine(o);  
  61.             }  
  62.    
  63.             // 测试查找  
  64.             Console.WriteLine("集合中是否包含值为0的元素?答案:" + (lst.Contains(0) ? "是" : "否"));  
  65.             Console.WriteLine("值为0的元素在第几个位置?答案:" + lst.IndexOf(0));  
  66.         }  
  67.     }  
  68. }  

0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值