C#学习笔记之——动态数组(ArrayList)
动态数组
ArrayList只能是一维,Array可以是多维的
- 动态的增加和减少元素
- 实现了ICollection和List和IEnumerable接口
- 灵活的设置数组大小
- 不安全的集合类型
- 其元素为值类型时效率不高(装箱和拆箱导致效率不高)
ArrayList常用的方法
//to create an ArrayList
ArrayList arrayList = new ArrayList();
//to add values
arrayList.Add(32);
arrayList.Add("Puma");
arrayList.Add('a');
//ArrayList can have different kinds of type of value
//to output
foreach (object obj in arrayList)
{
Console.Write(obj + " ");
}
Console.WriteLine();
//show the capacity
Console.WriteLine("the Capacity is:" + arrayList.Capacity);
Console.WriteLine("Adding one more element");
arrayList.Add(5);
Console.WriteLine("Now the Capacity is:" + arrayList.Capacity);
//count: gets the number of elements actually contained in ArrayList
Console.WriteLine("The elements in the ArrayList are:" + arrayList.Count);
//contains : Determines whether an element is in the ArrayList
if(arrayList.Contains(32))
Console.WriteLine("It exists!");
else
Console.WriteLine("It doesn'n exist");
//Insert: Insert an element into ArrayList at the specified index
arrayList.Insert(2,"real");
foreach (object obj in arrayList)
{
Console.Write(obj + " ");
}
Console.WriteLine();
//IndexOf:searches for the specified object and returns the zero-based index of the first occurrence within the entire ArrayList.
Console.WriteLine(arrayList.IndexOf(32));
//Remove:Removes the first occurrence of a specific object from the ArrayList
arrayList.Remove(32);
foreach (object obj in arrayList)
{
Console.Write(obj + " ");
}
Console.WriteLine();
//Reverse:Reverses the order of the elements in the entire ArrayList
arrayList.Reverse();
foreach (object obj in arrayList)
{
Console.Write(obj + " ");
}
Console.WriteLine();
//Sort:Sorts the elements in the entire ArrayList.
arrayList.Add(3);
arrayList.Add(42);
arrayList.Remove("Puma");
arrayList.Remove("real");
arrayList.Remove('a');
//before sorting
foreach (object obj in arrayList)
{
Console.Write(obj + " ");
}
Console.WriteLine();
arrayList.Sort();
//after sorting
foreach (object obj in arrayList)
{
Console.Write(obj + " ");
}
Console.WriteLine();