Java中ArrayList類的用法

 Java中ArrayList類的用法
1、什麼是ArrayList
ArrayList就是傳說中的動態數組,用MSDN中的說法,就是Array的複雜版本,它提供瞭如下一些好處:
動態的增加和減少元素
實現了ICollection和IList接口
靈活的設置數組的大小
2、如何使用ArrayList
最簡單的例子:
ArrayList List = new ArrayList();
for( int i=0;i <10;i++ ) //給數組增加10個Int元素
List.Add(i);
//..程序做一些處理
List.RemoveAt(5);//將第6個元素移除
for( int i=0;i <3;i++ ) //再增加3個元素
List.Add(i+20);
Int32[] values = (Int32[])List.ToArray(typeof(Int32));//返回ArrayList包含的數組
這是一個簡單的例子,雖然沒有包含ArrayList所有的方法,但是可以反映出ArrayList最常用的用法
3、ArrayList重要的方法和屬性
1)構造器
ArrayList提供了三個構造器:
public ArrayList();
默認的構造器,將會以默認(16)的大小來初始化內部的數組
public ArrayList(ICollection);
用一個ICollection對象來構造,並將該集合的元素添加到ArrayList
public ArrayList(int);
用指定的大小來初始化內部的數組
2)IsSynchronized屬性和ArrayList.Synchronized方法
IsSynchronized屬性指示當前的ArrayList實例是否支持線程同步,而ArrayList.Synchronized靜態方法則會返回一個ArrayList的線程同步的封裝。
如果使用非線程同步的實例,那麼在多線程訪問的時候,需要自己手動調用lock來保持線程同步,例如:
ArrayList list = new ArrayList();
//...
lock( list.SyncRoot ) //當ArrayList爲非線程包裝的時候,SyncRoot屬性其實就是它自己,但是爲了滿足ICollection的SyncRoot定義,這裏還是使用SyncRoot來保持源代碼的規範性
{
list.Add( “Add a Item” );
}
如果使用ArrayList.Synchronized方法返回的實例,那麼就不用考慮線程同步的問題,這個實例本身就是線程安全的,實際上ArrayList內部實現了一個保證線程同步的內部類,ArrayList.Synchronized返回的就是這個類的實例,它裏面的每個屬性都是用了lock關鍵字來保證線程同步。
3)Count屬性和Capacity屬性
Count屬性是目前ArrayList包含的元素的數量,這個屬性是隻讀的。
Capacity屬性是目前ArrayList能夠包含的最大數量,可以手動的設置這個屬性,但是當設置爲小於Count值的時候會引發一個異常。
4)Add、AddRange、Remove、RemoveAt、RemoveRange、Insert、InsertRange
這幾個方法比較類似
Add方法用於添加一個元素到當前列表的末尾
AddRange方法用於添加一批元素到當前列表的末尾
Remove方法用於刪除一個元素,通過元素本身的引用來刪除
RemoveAt方法用於刪除一個元素,通過索引值來刪除
RemoveRange用於刪除一批元素,通過指定開始的索引和刪除的數量來刪除
Insert用於添加一個元素到指定位置,列表後面的元素依次往後移動
InsertRange用於從指定位置開始添加一批元素,列表後面的元素依次往後移動
另外,還有幾個類似的方法:
Clear方法用於清除現有所有的元素
Contains方法用來查找某個對象在不在列表之中
其他的我就不一一累贅了,大家可以查看MSDN,上面講的更仔細
5)TrimSize方法
這個方法用於將ArrayList固定到實際元素的大小,當動態數組元素確定不在添加的時候,可以調用這個方法來釋放空餘的內存。
6)ToArray方法
這個方法把ArrayList的元素Copy到一個新的數組中。
4、ArrayList與數組轉換
例1:
ArrayList List = new ArrayList();
List.Add(1);
List.Add(2);
List.Add(3);
Int32[] values = (Int32[])List.ToArray(typeof(Int32));
例2:
ArrayList List = new ArrayList();
List.Add(1);
List.Add(2);
List.Add(3);
Int32[] values = new Int32[List.Count];
List.CopyTo(values);
上面介紹了兩種從ArrayList轉換到數組的方法
例3:
ArrayList List = new ArrayList();
List.Add( “string” );
List.Add( 1 );
//往數組中添加不同類型的元素
object[] values = List.ToArray(typeof(object)); //正確
string[] values = (string[])List.ToArray(typeof(string)); //錯誤
和數組不一樣,因爲可以轉換爲Object數組,所以往ArrayList裏面添加不同類型的元素是不會出錯的,但是當調用ArrayList方法的時候,要麼傳遞所有元素都可以正確轉型的類型或者Object類型,否則將會拋出無法轉型的異常。

5、ArrayList最佳使用建議
ArrayList與數組的差別,以及ArrayList的效率問題
1)ArrayList是Array的複雜版本
ArrayList內部封裝了一個Object類型的數組,從一般的意義來說,它和數組沒有本質的差別,甚至於ArrayList的許多方法,如Index、IndexOf、Contains、Sort等都是在內部數組的基礎上直接調用Array的對應方法。
2)內部的Object類型的影響
對於一般的引用類型來說,這部分的影響不是很大,但是對於值類型來說,往ArrayList裏面添加和修改元素,都會引起裝箱和拆箱的操作,頻繁的操作可能會影響一部分效率。
但是恰恰對於大多數人,多數的應用都是使用值類型的數組。
消除這個影響是沒有辦法的,除非你不用它,否則就要承擔一部分的效率損失,不過這部分的損失不會很大。
3)數組擴容
這是對ArrayList效率影響比較大的一個因素。
每當執行Add、AddRange、Insert、InsertRange等添加元素的方法,都會檢查內部數組的容量是否不夠了,如果是,它就會以當前容量的兩倍來重新構建一個數組,將舊元素Copy到新數組中,然後丟棄舊數組,在這個臨界點的擴容操作,應該來說是比較影響效率的。
例1:比如,一個可能有200個元素的數據動態添加到一個以默認16個元素大小創建的ArrayList中,將會經過:
16*2*2*2*2 = 256
四次的擴容纔會滿足最終的要求,那麼如果一開始就以:
ArrayList List = new ArrayList( 210 );
的方式創建ArrayList,不僅會減少4次數組創建和Copy的操作,還會減少內存使用。
例2:預計有30個元素而創建了一個ArrayList:
ArrayList List = new ArrayList(30);
在執行過程中,加入了31個元素,那麼數組會擴充到60個元素的大小,而這時候不會有新的元素再增加進來,而且有沒有調用TrimSize方法,那麼就有1次擴容的操作,並且浪費了29個元素大小的空間。如果這時候,用:
ArrayList List = new ArrayList(40);
那麼一切都解決了。
所以說,正確的預估可能的元素,並且在適當的時候調用TrimSize方法是提高ArrayList使用效率的重要途徑。
4)頻繁的調用IndexOf、Contains等方法(Sort、BinarySearch等方法經過優化,不在此列)引起的效率損失
首先,我們要明確一點,ArrayList是動態數組,它不包括通過Key或者Value快速訪問的算法,所以實際上調用IndexOf、Contains等方法是執行的簡單的循環來查找元素,所以頻繁的調用此類方法並不比你自己寫循環並且稍作優化來的快,如果有這方面的要求,建議使用Hashtable或SortedList等鍵值對的集合。
ArrayList al=new ArrayList();
al.Add("How");
al.Add("are");
al.Add("you!");
al.Add(100);
al.Add(200);
al.Add(300);
al.Add(1.2);
al.Add(22.8);


-------------------------------------------------------
System.Collections.ArrayList類是一個特殊的數組。通過添加和刪除元素,就可以動態改變數組的長度。
一.優點
1。支持自動改變大小的功能
2。可以靈活的插入元素
3。可以靈活的刪除元素
二.侷限性
跟一般的數組比起來,速度上差些
三.添加元素
1.publicvirtualintAdd(objectvalue);
將對象添加到ArrayList的結尾處
ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
內容爲abcde
2.publicvirtualvoidInsert(intindex,objectvalue);
將元素插入ArrayList的指定索引處
ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Insert(0,"aa");
結果爲aaabcde
3.publicvirtualvoidInsertRange(intindex,ICollectionc);
將集合中的某個元素插入ArrayList的指定索引處
ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
ArrayListlist2=newArrayList();
list2.Add("tt");
list2.Add("ttt");
aList.InsertRange(2,list2);
結果爲abtttttcde
四.刪除
a)publicvirtualvoidRemove(objectobj);
從ArrayList中移除特定對象的第一個匹配項,注意是第一個
ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Remove("a");
結果爲bcde
2.publicvirtualvoidRemoveAt(intindex);
移除ArrayList的指定索引處的元素
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.RemoveAt(0);
結果爲bcde
3.publicvirtualvoidRemoveRange(intindex,intcount);
從ArrayList中移除一定範圍的元素。Index表示索引,count表示從索引處開始的數目
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.RemoveRange(1,3);
結果爲ae
4.publicvirtualvoidClear();
從ArrayList中移除所有元素。
五.排序
a)publicvirtualvoidSort();
對ArrayList或它的一部分中的元素進行排序。
ArrayListaList=newArrayList();
aList.Add("e");
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
DropDownList1.DataSource=aList;//DropDownListDropDownList1;
DropDownList1.DataBind();
結果爲eabcd
ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Sort();//排序
DropDownList1.DataSource=aList;//DropDownListDropDownList1;
DropDownList1.DataBind();
結果爲abcde
b)publicvirtualvoidReverse();
將ArrayList或它的一部分中元素的順序反轉。
ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Reverse();//反轉
DropDownList1.DataSource=aList;//DropDownListDropDownList1;
DropDownList1.DataBind();
結果爲edcba
六.查找
a)publicvirtualintIndexOf(object);
b)publicvirtualintIndexOf(object,int);
c)publicvirtualintIndexOf(object,int,int);
返回ArrayList或它的一部分中某個值的第一個匹配項的從零開始的索引。沒找到返回-1。
ArrayListaList=newArrayList();
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
d)publicvirtualintLastIndexOf(object);
e)publicvirtualintLastIndexOf(object,int);
f)publicvirtualintLastIndexOf(object,int,int);
返回ArrayList或它的一部分中某個值的最後一個匹配項的從零開始的索引。
ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("a");//同0
aList.Add("d");
aList.Add("e");
intnIndex=aList.LastIndexOf("a");//值爲2而不是0
g)publicvirtualboolContains(objectitem);
確定某個元素是否在ArrayList中。包含返回true,否則返回false
七.其他
1.publicvirtualintCapacity{get;set;}
獲取或設置ArrayList可包含的元素數。
2.publicvirtualintCount{get;}
獲取ArrayList中實際包含的元素數。
Capacity是ArrayList可以存儲的元素數。Count是ArrayList中實際包含的元素數。Capacity總是大於或等於Count。如果在添加元素時,Count超過Capacity,則該列表的容量會通過自動重新分配內部數組加倍。
如果Capacity的值顯式設置,則內部數組也需要重新分配以容納指定的容量。如果Capacity被顯式設置爲0,則公共語言運行庫將其設置爲默認容量。默認容量爲16。
在調用Clear後,Count爲0,而此時Capacity切是默認容量16,而不是0
3.publicvirtualvoidTrimToSize();
將容量設置爲ArrayList中元素的實際數量。
如果不向列表中添加新元素,則此方法可用於最小化列表的內存系統開銷。
若要完全清除列表中的所有元素,請在調用TrimToSize之前調用Clear方法。截去空ArrayList會將ArrayList的容量設置爲默認容量,而不是零。
ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");//Count=5,Capacity=16,
aList.TrimToSize();//Count=Capacity=5;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章