C#的ArrayList

来源:互联网 发布:c语言input怎么用 编辑:程序博客网 时间:2024/06/18 11:14

ArrayList类是一个特殊的数组。它来自于System.Collections命名空间;通过添加和删除元素,就可以动态改变数组的长度。

一、优点

1)支持自动改变大小的功能
2)可以灵活的插入元素
3)可以灵活的删除元素

二、局限性

跟一般的数组比起来,速度上差些。

因为它是动态数组,初始化大小容量4,当数据存满时扩容是以当前数组容量大小的2倍扩容,之后再把数组元素一个一个的存入,数组在扩容时浪费一定的内存空间,和存储时间,而且,元素添加是一个装箱的过程,所以说,跟一般的数组比起来,速度上差些。

三、ArrayList初始化

ArrayList有三种初始化

 1)不初始化其容量 ArrayList al =new ArrayList();//默认容量为0,当数组容量满时数组会自动以当前数组容量的2倍扩容

 2 ) 初始化容量ArrayList al = new ArrayList(3);//初始容量为3

 3)以一个集合或数组初始化ArrayList al =new ArrayList(a);//a为集合或数组

四、添加元素

添加元素用其自带的方法Add(object value);

ArrayList al = newArrayList();

al.Add("a");

al.Add('B');

al.Add(1);

al.Add(15);

al.Add(5);

 输出为:a B 1 15 5

Insert(int index,object value)方法也可以用来将元素插入到索引处,不过其有一定的限制性,必须在数组长度以内插入数组

InsertRange(intindex, ICollection c)方法同Insert()一样

五、删除元素

al.Remove(object obj);//移除数组中的obj元素

al.RemoveAt(int index);//移除索引为index的数字元素

al.RemoveRange(int indext,intcount);//移除从索引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的遍历

1、Count属性可以获取ArrayList数组的长度,可以用for遍历数组

                               for (int i = 0; i< al.Count; i++ )

                              {

                                           Console.Write("{0}\t",al[i]);

                              }

2、用foreach遍历

                         foreach(object o in al)

                          {

                                  Console.Write("{0}\t", o);

                            }


初始化ArrayList的两种方法

方式一:
  ArrayList<String> list = new ArrayList<String>();
  String str01 = String("str01");
  String str02 = String("str02");
  list.add(str01);
  list.add(str02);
方式二:
  
ArrayList<String> list = new ArrayList<String>(){{add("str01"); add("str02");}}; 


0 0
原创粉丝点击