ArrayList类位于System.Collections;命名空间下,使用时需在命名空间区域添加using System.Collections;。它可以动态的添加和删除元素。可以将ArrayList类看作扩充了功能的数组,但它并不等同于数组。
与数组相比,ArrayList类提供了一下功能
a,数组的容量是固定的,而ArrayList的容量可以根据需要自动扩充。
b,ArrayList提供添加、删除和插入某一范围元素的方法,但在数组中,只能一次获取或设置一个元素值。
c,ArrayList提供将只读和固定大小包装返回集合的方法,而数组不提供。
d,ArrayList只能是一维形式,而数组可以是多维的。
1,ArrayList声明形式
a,声明ArrayList对象,但不定义大小
ArrayList list2 = new ArrayList();
foreach(var i in list2)
{
list2.Add(i);
}
b,声明ArrayList对象时,将数组元素添加到ArrayList中
double[] ab = new double[] { 6, 5, 7, 1, 2, 3, 4 };
ArrayList list = new ArrayList(ab);
c,声明时,指定ArrayList对象空间大小
ArrayList list3 = new ArrayList(10);
for(int i=0;i<list3.Count;i++)
{
list3.Add(i);
}
2,ArrayList元素的添加
a,Add()方法,用来将对象添加到ArrayList集合的结尾处。ArrayList允许null值作为有效值,并且允许重复的元素。
3,Insert()方法,用来将元素插入ArrayList集合的指定索引处。
a,list.Insert(index,value);index是索引,value是插入值
double[] ab = new double[] { 6, 5, 7, 1, 2, 3, 4 };
ArrayList list = new ArrayList(ab);
list.Insert(2,11);//2是索引,11是插入值
foreach(var i in list)
{
Console.WriteLine(i);
}
b,在ArrayList集合中插入一个数组,采用ListRange(index,一维数组)
double[] ac = new double[] { 6, 5, 7, 1, 2, 3, 4 };
double[] an = new double[] { 6, 5, 7 };
ArrayList list4 = new ArrayList(ac);
list4.InsertRange(2, an);
foreach(var i in list4)
{
Console.WriteLine("list4={0}",i);
}
4,ArrayList元素的删除
可以使用ArrayList类提供的Clear()方法、Remove()方法、RemoveAt()方法、RemoveRange()方法。
a,Clear()方法,用来宠ArrayList中移除所有元素。
double[] ac = new double[] { 6, 5, 7, 1, 2, 3, 4 };
ArrayList list4 = new ArrayList(ac);
list4.Clear();
b,Remove()方法,用来从ArrayList中移除特定对象的第一个匹配项。
double[] ac = new double[] { 6, 5, 7, 1, 2, 3, 4 };
ArrayList list4 = new ArrayList(ac);
list4.Remove(3);//移除的元素是3
c,RemoveAt()方法,用来移除ArrayList中指定索引处的元素。
double[] ac = new double[] { 6, 5, 7, 1, 2, 3, 4 };
ArrayList list4 = new ArrayList(ac);
list4.RemoveAt(3);//移除的元素是1
d,RemoveRange()方法,用来从ArrayList中移除一定范围的元素
double[] ac = new double[] { 6, 5, 7, 1, 2, 3, 4 };
ArrayList list4 = new ArrayList(ac);
list4.RemoveRange(2,3);//移除的元素是7,1,2
5,ArrayList元素的查找
可以使用ArrayList类提供的Contains()方法、IndexOf()方法、LastIndexOf()方法
a,Contains()方法,查找元素是否在集合中,输出true或者false
int[] ac = new int[] { 6, 5, 7, 1, 2, 3, 4 };
ArrayList list4 = new ArrayList(ac);
Console.WriteLine(list4.Contains(5));//结果为
b,IndexOf(value)方法,查找元素在集合中的索引
int[] ac = new int[] { 6, 5, 7, 1, 2, 3, 4 };
ArrayList list4 = new ArrayList(ac);
int bb = list4.IndexOf(5);
Console.WriteLine(bb);//输出结果为1
IndexOf(value,startIndex,num)方法,查找元素在集合中的索引.
value要查找的元素,startIndex查找的起始索引,num查找几个数
int[] ac = new int[] { 6, 5, 7, 1, 2, 3, 4 };
ArrayList list4 = new ArrayList(ac);
int bb = list4.IndexOf(5,0,3);//查找元素5,从索引0开始查找,查找3个数值,没有返回-1
Console.WriteLine(bb);//输出结果为1
c,LastIndexOf()方法,查找最后一个匹配项的索引位置
int[] ac = new int[] { 6, 5, 7, 1, 2, 3,5, 4,0 };
ArrayList list4 = new ArrayList(ac);
int cc = list4.LastIndexOf(5);//查找最后一个5所在的索引位置
Console.WriteLine(cc);//输出结果为6