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 'PrintValues

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> (in 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. 必须ArrayList先调用其Sort方法, 然后才能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的对象, 可以通过在运行时环境中enabled<gcAllowVeryLargeObjects>配置元素的属性设置为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.

ArrayList集合接受null为有效的值。The 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)

为特定 IList 创建 ArrayList 包装。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)

使用默认的比较器在整个已排序的 ArrayList 中搜索元素,并返回该元素从零开始的索引。Searches 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)

使用指定的比较器在整个已排序的 ArrayList 中搜索元素,并返回该元素从零开始的索引。Searches 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)

搜索指定的 Object,并返回 ArrayList 中从指定索引到最后一个元素的元素范围中第一个匹配项的从零开始索引。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)

搜索指定的 Object,并返回 ArrayList 中从指定索引开始,并包含指定元素数的元素范围中第一个匹配项的从零开始的索引。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)

在整个 ArrayList 中搜索指定的 Object,并返回最后一个匹配项的从零开始的索引。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)

搜索指定的 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 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 的浅表副本。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.

另请参阅