ArrayList类是一个特殊的数组。它来自于System.Collections命名空间;通过添加和删除元素,就可以动态改变数组的长度。
代码介绍一下。。。
using System;
using System.Collections;//arraylist的头文件
using System.Collections.Generic;//list的头文件
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication63
{
class fathder
{
}
class Program
{
ArrayList arrayList = new ArrayList();
List<int> li = new List<int>();//定义list的时候得定义list的类型,arraylist不用
static void Main(string[] args)
{
arrayList.Add(10);//往里面传参数的时候可以指定任意类型
arrayList.Add("nihao");
arrayList.Add(new fathder());
foreach (var item in arrayList)//可以用foreach便利ArrayList所有元素都当作object,所以访问元素时需要强制类型转换
{
Console.WriteLine(item);
}
li.Add(5);//指定类型后只能传指定类型的参数 List<T>保障了类型的安全性。在获取元素时无需进行类型转换
Console.ReadKey();
}
}
}
ArrayList初始化 ArrayList有三种初始化
1. 不初始化起容量 ArrayList al = new ArrayList();//默认容量为0,当数组容量满时数组会自动一当前数组容量的2倍扩容
2. 初始化容量ArrayList al = new ArrayList(3);//初始容量为3
3. 以一个集合或数组初始化ArrayList al = new ArrayList(a);//a为集合或数组
继续代码介绍。。。
添加元素
ArrayList arrayList = new ArrayList();
arrayList.Add(10);//往里面传参数的时候可以指定任意类型
arrayList.Add("nihao");
arrayList.Add(new fathder());
foreach (var item in arrayList)//可以用foreach便利ArrayList所有元素都当作object,所以访问元素时需要强制类型转换
{
Console.WriteLine(item);
}
移除元素
arrayList.Remove(object obj);//移除数组中的obj元素
arrayList.RemoveAt(int index);//移除索引为index的数字元素
arrayList.RemoveRange(int indext,int count);//移除从索引index开始,移除count个元素
查找元素
查找元素有Contains()、IndexOf()、LastIndexOf()3中方法
al.Contains(object obj);//查找数组中是否有obj元素,存在返回true;
IndexOf()有两个重载方法 用法如下:
1)、al.IndexOf(object obj);//从0开始查找obj元素,只第一个obj元素,并返回起在数组中的位置,如果不存在,返回-1;
2)、al.IndexOf(object obj,int startIndex); //从startIndex开始查找obj元素,只第一个obj元素,并返回起在数组中的位置,
3)、al.IndexOf(object obj,int startIndex,int count); 从startIndex开始想后查找count个元素,如果存在obj元素,则返回其在数组中的位置
al.LastIndexOf()方法与IndexOf()用法相同,它也有两个重载,其不同的是,LastIndexOf(obj)是查找要obj最后出现的位置
ArrayList的遍历
Count属性可以获取ArrayList数组的长度,可以用for遍历数组
for (int i = 0; i < al.Count;i++ )
{
Console.Write("{0}\t",al[i]);
}
用foreach遍历
foreach(object o in al)
{
Console.Write("{0}\t", o);
}