C# 動態數組(ArrayList)


動態數組(ArrayList)代表了可被單獨索引的對象的有序集合。它基本上可以替代一個數組。但是,與數組不同的是,您可以使用索引在指定的位置添加和移除項目,動態數組會自動重新調整它的大小。它也允許在列表中進行動態內存分配、增加、搜索、排序各項

一.引用

using System.Collections

二.優缺點

1.優點

1). 支持自動改變大小的功能

2). 可以靈活的插入元素

3). 可以靈活的刪除元素

4). 可以靈活訪問元素

2.缺點

跟一般的數組比起來,因obejct需進行裝箱拆箱操作,速度性能稍差

三.屬性說明

1.動態數組新增

ArrayList aList=new ArrayList();

1)將對象添加到ArrayList的結尾處

   對象:public virtual int Add(object value);

List.Add("a");

2)將元素插入ArrayList的指定索引處

對象:public virtual void Insert(int index,object value);

aList.Insert(0,"aa");

3)將集合中的某個元素插入ArrayList的指定索引處

對象:public virtual void InsertRange(int index,ICollectionc);

ArrayList list2=new ArrayList();
list2.Add("tt");
list2.Add("ttt");
aList.InsertRange(2,list2);

2.刪除

1)從ArrayList中移除特定對象的第一個匹配項,注意是第一個

對象:public virtual void Remove(object obj);

List.Remove("a");

2)移除ArrayList的指定索引處的元素

 對象:public virtual void RemoveAt(int index);

aList.RemoveAt(0);

3)從ArrayList中移除一定范圍的元素。Index表示索引,count表示從索引處開始的數目

對象:public virtual void RemoveRange(int index,int count);

aList.RemoveRange(1,3);

4)從ArrayList中移除所有元素

對象:public virtual void Clear();

aList.Clear();

3.排序

1)對ArrayList或它的一部分中的元素進行排序。

對象:public virtual void Sort();

aList.Sort();//排序

2)將ArrayList或它的一部分中元素的順序反轉。

對象:public virtual void Reverse();

aList.Reverse();//反轉

4.查找

1)返回ArrayList或它的一部分中某個值的第一個匹配項的從零開始的索引。沒找到返回-1。

對象:

 public virtual int IndexOf(object);

 public virtual int IndexOf(object,int);

 public virtual int IndexOf(object,int,int);

ArrayList aList=new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
intnIndex=aList.IndexOf(“a”);//1
nIndex=aList.IndexOf(“p”);//沒找到,-1

2)返回ArrayList或它的一部分中某個值的最后一個匹配項的從零開始的索引。

 public virtual int LastIndexOf(object);

 public virtual int LastIndexOf(object,int);

 public virtual int LastIndexOf(object,int,int);

ArrayList aList=new ArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("a");//同0
aList.Add("d");
aList.Add("e");
intnIndex=aList.LastIndexOf("a");//值為2而不是0

3)確定某個元素是否在ArrayList中。包含返回true,否則返回false

 public virtual bool Contains(object item);

bool bl=aList.Contains("a");

5.獲取數組中的元素

1.下面以整數為例,給出獲取某個元素的值的方法

ArrayList aList=new ArrayList();
for(int i=0;i<10;i++)
{
   aList.Add(i);
}

for(i=0;i<10;i++)
{
  Textbox1.text+=(int)aList[i]+" ";//獲取的方式基本與一般的數組相同,使用下標的方式進行
}

結果為:0 1 2 3 4 5 6 7 8 9

6.其它

1.獲取或設置ArrayList可包含的元素數。

對象:public virtual int Capacity{get;set;}

2.獲取ArrayList中實際包含的元素數。

對象:public virtual int Count{get;}

Capacity是ArrayList可以存儲的元素數。Count是ArrayList中實際包含的元素數。Capacity總是大於或等於Count。如果在添加元素時,Count超過Capacity,則該列表的容量會通過自動重新分配內部數組加倍。

如果Capacity的值顯式設置,則內部數組也需要重新分配以容納指定的容量。如果Capacity被顯式設置為0,則公共語言運行庫將其設置為默認容量。默認容量為16。

在調用Clear后,Count為0,而此時Capacity卻是默認容量16,而不是0

3.將容量設置為ArrayList中元素的實際數量。

對象:public virtual void TrimToSize();

 

原文鏈接:https://www.cnblogs.com/chenyongblog/p/3188816.html

 



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM