Array和ArrayList的区别
1:Array的容量是固定的,而ArrayList的容量可以根据需要自动扩充
2:ArrayList提供添加/插入或者移除某一段范围元素的方法;在Array中,只能一次获取或设置一个元素值
3:Array可以是多维的,但ArrayList只能是一维
using System; //Array public class Test { static void Main() { //第一种声明形式 int[] a = new int[2]; a[0] = 1; a[1] = 2; for (int i = 0; i < 2; i++) { Console.WriteLine(a[i]); } //第二种声明形式 int[] b = new int[]{3,4}; for (int i = 0; i < b.Length; i++) { Console.WriteLine(b[i]); } //第三种声明形式 int[] c = { 5, 6 }; foreach (int i in c) { Console.WriteLine(i); } } }
using System; using System.Collections; //ArrayList public class Test { static void Main() { ArrayList arrlst = new ArrayList(); string str; Console.WriteLine("Enter strings:"); while(true) { str = Console.ReadLine(); if (str == "exit") { break; } arrlst.Add(str);//向数组中添加元素 } //遍历数组 foreach (string s in arrlst) { Console.WriteLine(s); } } }
using System;//多维数组 public class Test { static void Main() { //声明并初始化一个二维数组 int[,] a = new int[2, 3]; int[,] b = new int[,]{{1,2,3}, {4,5,6}}; //遍历 foreach (int i in b) { Console.WriteLine(i); } } }