要将容量设置为ArrayList中元素的实际数量,代码如下-
using System; using System.Collections; public class Demo { public static void Main(String[] args) { ArrayList list1 = new ArrayList(); list1.Add("A"); list1.Add("B"); list1.Add("C"); list1.Add("D"); list1.Add("E"); list1.Add("F"); list1.Add("G"); list1.Add("H"); list1.Add("I"); Console.WriteLine("ArrayList1 的元素有..."); foreach (string res in list1) { Console.WriteLine(res); } ArrayList list2 = new ArrayList(); 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("ArrayList2 的元素有..."); foreach (string res in list2) { Console.WriteLine(res); } Console.WriteLine("ArrayList2 的元素数量为 = " + list2.Count); list2.RemoveAt(5); Console.WriteLine("ArrayList2 的元素数量为 (Updated) = " + list2.Count); Console.WriteLine("迭代ArrayList2的枚举器..."); IEnumerator demoEnum = list2.GetEnumerator(); while (demoEnum.MoveNext()) { Console.WriteLine(demoEnum.Current); } Console.WriteLine("ArrayList 的容量2 = " + list2.Capacity); list2.TrimToSize(); Console.WriteLine("ArrayList 的容量2 (updated) = " + list2.Capacity); } }
输出结果
这将产生以下输出-
ArrayList1 的元素有... A B C D E F G H I ArrayList2 的元素有... A B C D E F G H I ArrayList2 的元素数量为 = 9 ArrayList2 的元素数量为 (Updated) = 8 迭代ArrayList2的枚举器... A B C D E G H I ArrayList 的容量2 = 16 ArrayList 的容量2 (updated) = 8
现在让我们来看另一个示例-
using System; using System.Collections; public class Demo { public static void Main() { ArrayList list = new ArrayList(); list.Add("One"); list.Add("Two"); list.Add("Three"); list.Add("Four"); list.Add("Five"); list.Add("Six"); list.Add("Seven"); list.Add("Eight"); Console.WriteLine("ArrayList 元素有..."); foreach(string str in list) { Console.WriteLine(str); } Console.WriteLine("ArrayList 是只读吗? = "+list.IsReadOnly); Console.WriteLine("ArrayList中的元素有Six吗? = "+list.Contains("Six")); list.Insert(4, "Twelve"); Console.WriteLine("ArrayList 元素有...UPDATED"); foreach(string str in list) { Console.WriteLine(str); } Console.WriteLine("ArrayList 的容量 = " + list.Capacity); list.TrimToSize(); Console.WriteLine("ArrayList 的容量 (updated) = " + list.Capacity); } }
输出结果
这将产生以下输出-
ArrayList 元素有... One Two Three Four Five Six Seven Eight ArrayList 是只读吗? = False ArrayList中的元素有Six吗? = True ArrayList 元素有...UPDATED One Two Three Four Twelve Five Six Seven Eight ArrayList 的容量 = 16 ArrayList 的容量 (updated) = 9