c#之ArrayList与Array

来源:互联网 发布:家具下料软件 编辑:程序博客网 时间:2024/05/16 18:35

C#.Net 中ArrayList 与 Array的区别?(截取百度知道)

   

ArrayList 是数组的复杂版本。ArrayList 类提供在大多数 Collections 类中提供但不在 Array 类中提供的一些功能。例如: Array 的容量是固定的,而 ArrayList 的容量是根据需要自动扩展的。如果更改了 ArrayList.Capacity 属性的值,则自动进行内存重新分配和元素复制。 ArrayList 提供添加、插入或移除某一范围元素的方法。在 Array 中,您只能一次获取或设置一个元素的值。 使用 Synchronized 方法可以很容易地创建 ArrayList 的同步版本。而 Array 将一直保持它直到用户实现同步为止。 ArrayList 提供将只读和固定大小包装返回到集合的方法。而 Array 不提供。 另一方面,Array 提供 ArrayList 所不具有的某些灵活性。例如: 可以设置 Array 的下限,但 ArrayList 的下限始终为零。 Array 可以具有多个维度,而 ArrayList 始终只是一维的。 特定类型(不包括 Object)的 Array 的性能比 ArrayList 好,这是因为 ArrayList 的元素属于 Object 类型,所以在存储或检索值类型时通常发生装箱和取消装箱。 要求一个数组的大多数情况也可以代之以使用 ArrayList。它更易于使用,并且通常具有与 Object 类型的数组类似的性能。Array 位于 System 命名空间中;ArrayList 位于 System.Collections 命名空间中。
下面的复制示例演示如何将 ArrayList 的元素复制到字符串数组。
using System;using System.Collections;public class SamplesArrayList  {    public static void Main()  {       // Creates and initializes a new ArrayList.      ArrayList myAL = new ArrayList();      myAL.Add( "The" );      myAL.Add( "quick" );      myAL.Add( "brown" );      myAL.Add( "fox" );      myAL.Add( "jumped" );      myAL.Add( "over" );      myAL.Add( "the" );      myAL.Add( "lazy" );      myAL.Add( "dog" );       // Displays the values of the ArrayList.      Console.WriteLine( "The ArrayList contains the following values:" );      PrintIndexAndValues( myAL );       // Copies the elements of the ArrayList to a string array.      String[] myArr = (String[]) myAL.ToArray( typeof( string ) );      // Displays the contents of the string array.      Console.WriteLine( "The string array contains the following values:" );      PrintIndexAndValues( myArr );   }    public static void PrintIndexAndValues( ArrayList myList )  {      int i = 0;      foreach ( Object o in myList )         Console.WriteLine( "\t[{0}]:\t{1}", i++, o );      Console.WriteLine();   }   public static void PrintIndexAndValues( String[] myArr )  {      for ( int i = 0; i < myArr.Length; i++ )         Console.WriteLine( "\t[{0}]:\t{1}", i, myArr[i] );      Console.WriteLine();   }}/* This code produces the following output.The ArrayList contains the following values:        [0]:    The        [1]:    quick        [2]:    brown        [3]:    fox        [4]:    jumped        [5]:    over        [6]:    the        [7]:    lazy        [8]:    dogThe string array contains the following values:        [0]:    The        [1]:    quick        [2]:    brown        [3]:    fox        [4]:    jumped        [5]:    over        [6]:    the        [7]:    lazy        [8]:    dog*/

(待续......)

原创粉丝点击