在 C# 中创建一个拥有指定初始容量的 ArrayList
要创建具有指定初始容量的 ArrayList,代码如下所示 -
示例
using System; using System.Collections; public class Demo { public static void Main(String[] args) { ArrayList list1 = new ArrayList(5); list1.Add("A"); list1.Add("B"); list1.Add("C"); list1.Add("D"); Console.WriteLine("Capacity in ArrayList1 = "+list1.Capacity); Console.WriteLine("Elements in ArrayList1..."); foreach (string res in list1) { Console.WriteLine(res); } ArrayList list2 = new ArrayList(10); list2.Add("A"); list2.Add("B"); list2.Add("C"); list2.Add("D"); list2.Add("E"); list2.Add("F"); list2.Add("G"); list2.Add("H"); list2.Add("I"); Console.WriteLine("Capacity in ArrayList2 = "+list2.Capacity); Console.WriteLine("Elements in ArrayList2..."); foreach (string res in list2) { Console.WriteLine(res); } Console.WriteLine("Is ArrayList1 equal to ArrayList2? = "+list1.Equals(list2)); list2.RemoveRange(3, 2); Console.WriteLine("Elements in ArrayList2 after removing elements in a range..."); foreach (string res in list2) { Console.WriteLine(res); } Console.WriteLine("Capacity in ArrayList2 = "+list2.Capacity); } }
输出
这将产生以下输出 -
Capacity in ArrayList1 = 5 Elements in ArrayList1... A B C D Capacity in ArrayList2 = 10 Elements in ArrayList2... A B C D E F G H I Is ArrayList1 equal to ArrayList2? = False Elements in ArrayList2 after removing elements in a range... A B C F G H I Capacity in ArrayList2 = 10
示例
让我们看另一个例子 -
using System; using System.Collections; public class Demo { public static void Main(String[] args) { ArrayList list = new ArrayList(5); list.Add("A"); list.Add("B"); list.Add("C"); list.Add("D"); Console.WriteLine("Capacity in ArrayList = "+list.Capacity); Console.WriteLine("Count of elements in ArrayList = "+list.Count); Console.WriteLine("Elements in ArrayList..."); foreach (string res in list) { Console.WriteLine(res); } list.Clear(); Console.WriteLine("Capacity in ArrayList = "+list.Capacity); Console.WriteLine("Count of elements in ArrayList = "+list.Count); } }
输出
这将产生以下输出 -
Capacity in ArrayList = 5 Count of elements in ArrayList = 4 Elements in ArrayList... A B C D Capacity in ArrayList = 5 Count of elements in ArrayList = 0
广告