Array,ArrayList和List有什么区别?

Array,ArrayList和List有什么区别?

问题描述:

我想知道 Array ArrayList List (它们都有相似的概念)之间的确切区别是什么?您会在另一个上使用.

I am wondering what the exact difference is between a Array, ArrayList and a List (as they all have similar concepts) and where you would use one over the other.

示例:

数组
对于 Array ,我们只能添加在此示例中声明为 int 的类型.

Example:

Array
For the Array we can only add types that we declare for this example an int.

int[] Array = new Int[5]; //Instansiation of an array
for(int i = 0; i < Array.Length; i++)
{
   Array[i] = i + 5; //Add values to each array index
}

ArrayList
我们可以像 Array

ArrayList
We can add values just like a Array

ArrayList arrayList = new ArrayList();
arrayList.Add(6);
arrayList.Add(8);

列表
同样,我们可以像在 Array

List
Again we can add values like we do in an Array

List<int> list = new List<int>();
list.Add(6);
List.Add(8);

我知道在列表中,您可以使用通用类型 ,这样您就可以传递在 Array 中无法使用的任何类型.但我的确切问题是:

I know that in a List you can have the generic type so you can pass in any type that you cannot do in an Array but my exact questions are:

  • 您将在哪里使用另一个?
  • 这三个功能之间的确切区别是明智的吗?

它们是不同的对象类型.它们具有不同的功能,并以不同的方式存储数据.您也可以问小数和DateTime有什么区别.

They are different object types. They have different capabilities and store their data in different ways. You may as well ask what is the difference between a decimal and a DateTime.

分配后,数组(System.Array)的大小固定.您不能向其中添加项目或从中删除项目.同样,所有元素必须是相同的类型.因此,无论是在内存还是性能方面,它都是类型安全的,并且也是三者中效率最高的.此外,System.Array支持多个维度(即,它具有 Rank 属性),而List和ArrayList则没有(尽管您可以创建列表列表或ArrayList的ArrayList).

An Array (System.Array) is fixed in size once it is allocated. You can't add items to it or remove items from it. Also, all the elements must be the same type. As a result, it is type safe, and is also the most efficient of the three, both in terms of memory and performance. Also, System.Array supports multiple dimensions (i.e. it has a Rank property) while List and ArrayList do not (although you can create a List of Lists or an ArrayList of ArrayLists, if you want to).

ArrayList是一个灵活的数组,其中包含对象列表.您可以在其中添加和删除项目,它会自动处理分配的空间.如果将值类型存储在其中,则将它们装箱并取消装箱,这可能会导致效率低下.此外,它也不是类型安全的.

An ArrayList is a flexible array which contains a list of objects. You can add and remove items from it and it automatically deals with allocating space. If you store value types in it, they are boxed and unboxed, which can be a bit inefficient. Also, it is not type-safe.

A List<>利用泛型;它本质上是ArrayList的类型安全版本.这意味着没有装箱或拆箱(提高性能),并且如果您尝试添加错误类型的项目,则会生成编译时错误.

A List<> leverages generics; it is essentially a type-safe version of ArrayList. This means there is no boxing or unboxing (which improves performance) and if you attempt to add an item of the wrong type it'll generate a compile-time error.