ArrayList ArrayList ArrayList ArrayList Class

定義

使用大小會視需要動態增加的陣列,實作 IList 介面。Implements the IList interface using an array whose size is dynamically increased as required.

public ref class ArrayList : ICloneable, System::Collections::IList
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class ArrayList : ICloneable, System.Collections.IList
type ArrayList = class
    interface IList
    interface ICloneable
    interface ICollection
    interface IEnumerable
Public Class ArrayList
Implements ICloneable, IList
繼承
ArrayListArrayListArrayListArrayList
衍生
屬性
實作

範例

下列範例顯示如何建立和初始化ArrayList , 以及如何顯示其值。The following example shows how to create and initialize an ArrayList and how to display its values.

using namespace System;
using namespace System::Collections;
void PrintValues( IEnumerable^ myList );
int main()
{
   
   // Creates and initializes a new ArrayList.
   ArrayList^ myAL = gcnew ArrayList;
   myAL->Add( "Hello" );
   myAL->Add( "World" );
   myAL->Add( "!" );
   
   // Displays the properties and values of the ArrayList.
   Console::WriteLine( "myAL" );
   Console::WriteLine( "    Count:    {0}", myAL->Count );
   Console::WriteLine( "    Capacity: {0}", myAL->Capacity );
   Console::Write( "    Values:" );
   PrintValues( myAL );
}

void PrintValues( IEnumerable^ myList )
{
   IEnumerator^ myEnum = myList->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Object^ obj = safe_cast<Object^>(myEnum->Current);
      Console::Write( "   {0}", obj );
   }

   Console::WriteLine();
}

/* 
This code produces output similar to the following:

myAL
    Count:    3
    Capacity: 4
    Values:   Hello   World   !

*/
using System;
using System.Collections;
public class SamplesArrayList  {

   public static void Main()  {

      // Creates and initializes a new ArrayList.
      ArrayList myAL = new ArrayList();
      myAL.Add("Hello");
      myAL.Add("World");
      myAL.Add("!");

      // Displays the properties and values of the ArrayList.
      Console.WriteLine( "myAL" );
      Console.WriteLine( "    Count:    {0}", myAL.Count );
      Console.WriteLine( "    Capacity: {0}", myAL.Capacity );
      Console.Write( "    Values:" );
      PrintValues( myAL );
   }

   public static void PrintValues( IEnumerable myList )  {
      foreach ( Object obj in myList )
         Console.Write( "   {0}", obj );
      Console.WriteLine();
   }

}


/* 
This code produces output similar to the following:

myAL
    Count:    3
    Capacity: 4
    Values:   Hello   World   !

*/
Imports System.Collections

Public Class SamplesArrayList    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new ArrayList.
        Dim myAL As New ArrayList()
        myAL.Add("Hello")
        myAL.Add("World")
        myAL.Add("!")
        
        ' Displays the properties and values of the ArrayList.
        Console.WriteLine("myAL")
        Console.WriteLine("    Count:    {0}", myAL.Count)
        Console.WriteLine("    Capacity: {0}", myAL.Capacity)
        Console.Write("    Values:")
        PrintValues(myAL)
    End Sub

    Public Shared Sub PrintValues(myList As IEnumerable)
        Dim obj As [Object]
        For Each obj In  myList
            Console.Write("   {0}", obj)
        Next obj
        Console.WriteLine()
    End Sub

End Class


' This code produces output similar to the following:
' 
' myAL
'     Count:    3
'     Capacity: 4
'     Values:   Hello   World   !

備註

重要

我們不建議您將類別用於ArrayList新的開發。We don't recommend that you use the ArrayList class for new development. 相反地, 我們建議您使用泛型List<T>類別。Instead, we recommend that you use the generic List<T> class. ArrayList類別是設計用來保存不同的物件集合。The ArrayList class is designed to hold heterogeneous collections of objects. 不過, 它不一定會提供最佳效能。However, it does not always offer the best performance. 相反地, 我們建議下列各項:Instead, we recommend the following:

  • 針對異類物件集合, 請使用List<Object> (在中C#) 或List(Of Object) (Visual Basic) 類型。For a heterogeneous collection of objects, use the List<Object> (in C#) or List(Of Object) (in Visual Basic) type.
  • 若為物件的同質集合, 請List<T>使用類別。For a homogeneous collection of objects, use the List<T> class.
    如需這些類別的List<T>相對效能討論, 請參閱參考主題中的效能考慮See Performance Considerations in the List<T> reference topic for a discussion of the relative performance of these classes. 如需使用泛型而非泛型集合類型的一般資訊, 請參閱在 GitHub 上不應使用非泛型集合See Non-generic collections shouldn't be used on GitHub for general information on the use of generic instead of non-generic collection types.

ArrayList不保證會排序。The ArrayList is not guaranteed to be sorted. 您必須先呼叫ArrayListSort方法來排序, 才能BinarySearch執行需要ArrayList排序的作業 (例如)。You must sort the ArrayList by calling its Sort method prior to performing operations (such as BinarySearch) that require the ArrayList to be sorted. 若要維護自動排序為新元素的集合, 您可以使用SortedSet<T>類別。To maintain a collection that is automatically sorted as new elements are added, you can use the SortedSet<T> class.

的容量ArrayListArrayList可以保存的元素數目。The capacity of an ArrayList is the number of elements the ArrayList can hold. 當專案新增至時ArrayList, 會視需要透過重新配置來自動增加容量。As elements are added to an ArrayList, the capacity is automatically increased as required through reallocation. 您可以藉由呼叫TrimToSize或明確Capacity設定屬性來降低容量。The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly.

僅 .NET Framework: 對於非常大型ArrayList的物件, 您可以在執行時間環境中, 將<gcAllowVeryLargeObjects> configuration 專案的enabled屬性設為true , 以將64位系統上的最大容量增加到2000000000個元素。.NET Framework only: For very large ArrayList objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the <gcAllowVeryLargeObjects> configuration element to true in the run-time environment.

這個集合中的專案可以使用整數索引來存取。Elements in this collection can be accessed using an integer index. 這個集合中的索引是以零為基底。Indexes in this collection are zero-based.

集合會接受null做為有效的值。 ArrayListThe ArrayList collection accepts null as a valid value. 它也允許重複的元素。It also allows duplicate elements.

不支援使用多維陣列做為ArrayList集合中的元素。Using multidimensional arrays as elements in an ArrayList collection is not supported.

建構函式

ArrayList() ArrayList() ArrayList() ArrayList()

初始化 ArrayList 類別的新執行個體,這個執行個體為空白且具有預設的初始容量。Initializes a new instance of the ArrayList class that is empty and has the default initial capacity.

ArrayList(ICollection) ArrayList(ICollection) ArrayList(ICollection) ArrayList(ICollection)

初始化 ArrayList 類別的新執行個體,其含有從指定的集合複製過來的項目且具有與複製項目數一樣的初始容量。Initializes a new instance of the ArrayList class that contains elements copied from the specified collection and that has the same initial capacity as the number of elements copied.

ArrayList(Int32) ArrayList(Int32) ArrayList(Int32) ArrayList(Int32)

為具有指定初始容量且為空的 ArrayList 類別,初始化新的執行個體。Initializes a new instance of the ArrayList class that is empty and has the specified initial capacity.

屬性

Capacity Capacity Capacity Capacity

取得或設定 ArrayList 可包含的項目數目。Gets or sets the number of elements that the ArrayList can contain.

Count Count Count Count

取得 ArrayList 中實際包含的項目數目。Gets the number of elements actually contained in the ArrayList.

IsFixedSize IsFixedSize IsFixedSize IsFixedSize

取得值,指出 ArrayList 是否有固定的大小。Gets a value indicating whether the ArrayList has a fixed size.

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

取得值,指出 ArrayList 是否唯讀。Gets a value indicating whether the ArrayList is read-only.

IsSynchronized IsSynchronized IsSynchronized IsSynchronized

取得值,這個值表示對 ArrayList 的存取是否同步 (安全執行緒)。Gets a value indicating whether access to the ArrayList is synchronized (thread safe).

Item[Int32] Item[Int32] Item[Int32] Item[Int32]

在指定的索引位置上取得或設定項目。Gets or sets the element at the specified index.

SyncRoot SyncRoot SyncRoot SyncRoot

取得可用以同步存取 ArrayList 的物件。Gets an object that can be used to synchronize access to the ArrayList.

方法

Adapter(IList) Adapter(IList) Adapter(IList) Adapter(IList)

建立特定 IListArrayList 包裝函式。Creates an ArrayList wrapper for a specific IList.

Add(Object) Add(Object) Add(Object) Add(Object)

將物件加入至 ArrayList 的末端。Adds an object to the end of the ArrayList.

AddRange(ICollection) AddRange(ICollection) AddRange(ICollection) AddRange(ICollection)

ICollection 的項目加入 ArrayList 的結尾。Adds the elements of an ICollection to the end of the ArrayList.

BinarySearch(Int32, Int32, Object, IComparer) BinarySearch(Int32, Int32, Object, IComparer) BinarySearch(Int32, Int32, Object, IComparer) BinarySearch(Int32, Int32, Object, IComparer)

使用指定的比較子在已經過排序之 ArrayList 內,搜尋某範圍的項目,並傳回該項目以零為起始的索引。Searches a range of elements in the sorted ArrayList for an element using the specified comparer and returns the zero-based index of the element.

BinarySearch(Object) BinarySearch(Object) BinarySearch(Object) BinarySearch(Object)

使用預設的比較子並傳回項目以零為起始的索引,來搜尋項目之整個排序的 ArrayListSearches the entire sorted ArrayList for an element using the default comparer and returns the zero-based index of the element.

BinarySearch(Object, IComparer) BinarySearch(Object, IComparer) BinarySearch(Object, IComparer) BinarySearch(Object, IComparer)

使用指定的比較子並傳回項目以零為起始的索引,來搜尋項目之整個排序的 ArrayListSearches the entire sorted ArrayList for an element using the specified comparer and returns the zero-based index of the element.

Clear() Clear() Clear() Clear()

移除 ArrayList 中的所有項目。Removes all elements from the ArrayList.

Clone() Clone() Clone() Clone()

建立 ArrayList 的淺層複本。Creates a shallow copy of the ArrayList.

Contains(Object) Contains(Object) Contains(Object) Contains(Object)

判斷某項目是否在 ArrayList 中。Determines whether an element is in the ArrayList.

CopyTo(Array) CopyTo(Array) CopyTo(Array) CopyTo(Array)

從目標陣列的開頭開始,將整個 ArrayList 複製至相容的一維 ArrayCopies the entire ArrayList to a compatible one-dimensional Array, starting at the beginning of the target array.

CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32)

從目標陣列的指定索引開始,將整個 ArrayList 複製到相容的一維 ArrayCopies the entire ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array.

CopyTo(Int32, Array, Int32, Int32) CopyTo(Int32, Array, Int32, Int32) CopyTo(Int32, Array, Int32, Int32) CopyTo(Int32, Array, Int32, Int32)

從目標陣列的指定索引開始,將項目範圍從 ArrayList 複製至相容的一維 ArrayCopies a range of elements from the ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
FixedSize(ArrayList) FixedSize(ArrayList) FixedSize(ArrayList) FixedSize(ArrayList)

傳回具有固定大小的 ArrayList 包裝函式。Returns an ArrayList wrapper with a fixed size.

FixedSize(IList) FixedSize(IList) FixedSize(IList) FixedSize(IList)

傳回具有固定大小的 IList 包裝函式。Returns an IList wrapper with a fixed size.

GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

傳回整個 ArrayList 的列舉值。Returns an enumerator for the entire ArrayList.

GetEnumerator(Int32, Int32) GetEnumerator(Int32, Int32) GetEnumerator(Int32, Int32) GetEnumerator(Int32, Int32)

傳回適用於 ArrayList 中某段範圍項目的列舉程式。Returns an enumerator for a range of elements in the ArrayList.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetRange(Int32, Int32) GetRange(Int32, Int32) GetRange(Int32, Int32) GetRange(Int32, Int32)

傳回 ArrayList,代表來源 ArrayList 中項目的子集。Returns an ArrayList which represents a subset of the elements in the source ArrayList.

GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
IndexOf(Object) IndexOf(Object) IndexOf(Object) IndexOf(Object)

搜尋指定的 Object,並傳回在整個 ArrayList 中第一個符合項目之以零為起始的索引。Searches for the specified Object and returns the zero-based index of the first occurrence within the entire ArrayList.

IndexOf(Object, Int32) IndexOf(Object, Int32) IndexOf(Object, Int32) IndexOf(Object, Int32)

ArrayList 中從指定的索引開始到最後一個項目這段範圍內,搜尋指定的 Object 第一次出現的位置,並傳回其索引值 (索引以零起始)。Searches for the specified Object and returns the zero-based index of the first occurrence within the range of elements in the ArrayList that extends from the specified index to the last element.

IndexOf(Object, Int32, Int32) IndexOf(Object, Int32, Int32) IndexOf(Object, Int32, Int32) IndexOf(Object, Int32, Int32)

ArrayList 中從指定索引開始且包含指定項目個數的範圍內,搜尋指定的 Object 並傳回第一次出現的以零為起始的索引。Searches for the specified Object and returns the zero-based index of the first occurrence within the range of elements in the ArrayList that starts at the specified index and contains the specified number of elements.

Insert(Int32, Object) Insert(Int32, Object) Insert(Int32, Object) Insert(Int32, Object)

將項目插入至 ArrayList 中指定的索引位置。Inserts an element into the ArrayList at the specified index.

InsertRange(Int32, ICollection) InsertRange(Int32, ICollection) InsertRange(Int32, ICollection) InsertRange(Int32, ICollection)

將集合的項目插入位於指定索引的 ArrayList 中。Inserts the elements of a collection into the ArrayList at the specified index.

LastIndexOf(Object) LastIndexOf(Object) LastIndexOf(Object) LastIndexOf(Object)

搜尋指定的 Object,並傳回在整個 ArrayList 中最後一個符合項目之以零為起始的索引。Searches for the specified Object and returns the zero-based index of the last occurrence within the entire ArrayList.

LastIndexOf(Object, Int32) LastIndexOf(Object, Int32) LastIndexOf(Object, Int32) LastIndexOf(Object, Int32)

ArrayList 中從第一個項目開始到指定的索引這個範圍內,搜尋指定的 Object,並傳回最後一次出現的索引值 (以零為起始)。Searches for the specified Object and returns the zero-based index of the last occurrence within the range of elements in the ArrayList that extends from the first element to the specified index.

LastIndexOf(Object, Int32, Int32) LastIndexOf(Object, Int32, Int32) LastIndexOf(Object, Int32, Int32) LastIndexOf(Object, Int32, Int32)

搜尋指定的 Object,並傳回 ArrayList 中包含指定之項目數且結束於指定之索引的項目範圍內,最後一個相符項目之以零為起始的索引。Searches for the specified Object and returns the zero-based index of the last occurrence within the range of elements in the ArrayList that contains the specified number of elements and ends at the specified index.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
ReadOnly(ArrayList) ReadOnly(ArrayList) ReadOnly(ArrayList) ReadOnly(ArrayList)

傳回唯讀的 ArrayList 包裝函式。Returns a read-only ArrayList wrapper.

ReadOnly(IList) ReadOnly(IList) ReadOnly(IList) ReadOnly(IList)

傳回唯讀的 IList 包裝函式。Returns a read-only IList wrapper.

Remove(Object) Remove(Object) Remove(Object) Remove(Object)

ArrayList 移除特定物件之第一個符合的元素。Removes the first occurrence of a specific object from the ArrayList.

RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32)

移除 ArrayList 之指定索引處的項目。Removes the element at the specified index of the ArrayList.

RemoveRange(Int32, Int32) RemoveRange(Int32, Int32) RemoveRange(Int32, Int32) RemoveRange(Int32, Int32)

ArrayList 移除的項目範圍。Removes a range of elements from the ArrayList.

Repeat(Object, Int32) Repeat(Object, Int32) Repeat(Object, Int32) Repeat(Object, Int32)

傳回 ArrayList,其項目是指定值的複本。Returns an ArrayList whose elements are copies of the specified value.

Reverse() Reverse() Reverse() Reverse()

反轉整個 ArrayList 中項目的順序。Reverses the order of the elements in the entire ArrayList.

Reverse(Int32, Int32) Reverse(Int32, Int32) Reverse(Int32, Int32) Reverse(Int32, Int32)

反向指定範圍中項目的順序。Reverses the order of the elements in the specified range.

SetRange(Int32, ICollection) SetRange(Int32, ICollection) SetRange(Int32, ICollection) SetRange(Int32, ICollection)

ArrayList 中項目的範圍內複製集合的項目。Copies the elements of a collection over a range of elements in the ArrayList.

Sort() Sort() Sort() Sort()

排序整個 ArrayList 中的項目。Sorts the elements in the entire ArrayList.

Sort(IComparer) Sort(IComparer) Sort(IComparer) Sort(IComparer)

使用指定的比較子來排序在整個 ArrayList 中的項目。Sorts the elements in the entire ArrayList using the specified comparer.

Sort(Int32, Int32, IComparer) Sort(Int32, Int32, IComparer) Sort(Int32, Int32, IComparer) Sort(Int32, Int32, IComparer)

使用指定的比較子對 ArrayList 中某段範圍內的項目進行排序。Sorts the elements in a range of elements in ArrayList using the specified comparer.

Synchronized(ArrayList) Synchronized(ArrayList) Synchronized(ArrayList) Synchronized(ArrayList)

傳回已同步 (安全執行緒) 的 ArrayList 包裝函式。Returns an ArrayList wrapper that is synchronized (thread safe).

Synchronized(IList) Synchronized(IList) Synchronized(IList) Synchronized(IList)

傳回已同步 (安全執行緒) 的 IList 包裝函式。Returns an IList wrapper that is synchronized (thread safe).

ToArray() ToArray() ToArray() ToArray()

ArrayList 的項目複製到新的 Object 陣列。Copies the elements of the ArrayList to a new Object array.

ToArray(Type) ToArray(Type) ToArray(Type) ToArray(Type)

ArrayList 的項目複製到指定項目類型的新陣列。Copies the elements of the ArrayList to a new array of the specified element type.

ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)
TrimToSize() TrimToSize() TrimToSize() TrimToSize()

將容量設為 ArrayList 中的實際項目數目。Sets the capacity to the actual number of elements in the ArrayList.

擴充方法

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

根據指定的型別來篩選 IEnumerable 的項目。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

啟用查詢的平行化作業。Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryableConverts an IEnumerable to an IQueryable.

適用於

執行緒安全性

此類型的Shared公用靜態 (在 Visual Basic 中) 成員是安全線程。Public static (Shared in Visual Basic) members of this type are thread safe. 不保證任何執行個體成員是安全執行緒。Any instance members are not guaranteed to be thread safe.

只要不修改集合,就可以同時支援多個讀取器。ArrayListAn ArrayList can support multiple readers concurrently, as long as the collection is not modified. 為了保證的執行緒安全性ArrayList, 所有作業都必須透過Synchronized(IList)方法所傳回的包裝函式來完成。To guarantee the thread safety of the ArrayList, all operations must be done through the wrapper returned by the Synchronized(IList) method.

透過集合進行列舉在本質上並非安全執行緒程序。Enumerating through a collection is intrinsically not a thread-safe procedure. 即使集合經過同步化,其他的執行緒仍可修改該集合,使列舉值擲回例外狀況。Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. 若要保證列舉過程的執行緒安全,您可以在整個列舉過程中鎖定集合,或攔截由其他執行緒的變更所造成的例外狀況。To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

另請參閱