Array、ArrayList 和 List 之间有什么区别? [英] What is the difference between an Array, ArrayList and a List?

查看:28
本文介绍了Array、ArrayList 和 List 之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 ArrayArrayListList 之间的确切区别是什么(因为它们都有相似的概念)以及在哪里你会用一个而不是另一个.

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
我们可以像数组

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

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

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

我知道在 List 中,您可以拥有泛型类型 ,因此您可以传入在 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:

  • 你会在哪里使用一个?
  • 三者之间在功能方面的确切区别?

推荐答案

它们是不同的对象类型.它们具有不同的功能并以不同的方式存储数据.

They are different object types. They have different capabilities and store their data in different ways.

数组 (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.

这篇关于Array、ArrayList 和 List 之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆