📜  C#|数组与ArrayList

📅  最后修改于: 2021-05-29 21:32:37             🧑  作者: Mango

数组:数组是一组由通用名称引用的相似类型的变量。

例子:

// C# program to demonstrate the Arrays
using System;
  
class GFG {
  
    // Main Method
    public static void Main(string[] args)
    {
  
        // creating array
        int[] arr = new int[4];
  
        // initializing array
        arr[0] = 47;
        arr[1] = 77;
        arr[2] = 87;
        arr[3] = 97;
  
        // traversing array
        for (int i = 0; i < arr.Length; i++) {
  
            Console.WriteLine(arr[i]);
        }
    }
}
输出:
47
77
87
97

要了解有关数组的更多信息,请参考C#| Java。数组

ArrayList: ArrayList表示可以单独索引的对象的有序集合。基本上,它是数组的替代方法。它还允许动态分配内存,添加,搜索和排序列表中的项目。

例子:

// C# program to illustrate the ArrayList
using System;
using System.Collections;
  
class GFG {
  
    // Main Method
    public static void Main(string[] args)
    {
  
        // Create a list of strings
        ArrayList al = new ArrayList();
        al.Add("Ajay");
        al.Add("Ankit");
        al.Add(10);
        al.Add(10.10);
  
        // Iterate list element using foreach loop
        foreach(var names in al)
        {
            Console.WriteLine(names);
        }
    }
}
输出:
Ajay
Ankit
10
10.1

要了解有关ArrayList的更多信息,请参考C#| Java。 ArrayList类

Array和ArrayList之间的区别

Feature Array ArrayList
Memory This has fixed size and can’t increase or decrease dynamically. Size can be increase or decrease dynamically.
Namespace Arrays belong to System.Array namespace ArrayList belongs to System.Collection namespace.
Data Type In Arrays, we can store only one datatype either int, string, char etc. In ArrayList we can store different datatype variables.
Operation Speed Insertion and deletion operation is fast. Insertion and deletion operation in ArrayList is slower than an Array.
Typed Arrays are strongly typed which means it can store only specific type of items or elements. Arraylist are not strongly typed.
null Array cannot accept null. ArrayList can accepts null.