更改数组大小 [英] change array size
问题描述
是否可以在声明后更改数组大小?如果没有,是否有任何替代数组的方法?
我不想创建一个大小为 1000 的数组,但是我在创建它时不知道数组的大小.
Is it possible to change an array size after declaration?
If not, is there any alternative to arrays?
I do not want to create an array with a size of 1000, but I do not know the size of the array when I'm creating it.
推荐答案
不,请尝试使用强类型 列表 代替.
No, try using a strongly typed List instead.
例如:
代替使用
int[] myArray = new int[2];
myArray[0] = 1;
myArray[1] = 2;
你可以这样做:
List<int> myList = new List<int>();
myList.Add(1);
myList.Add(2);
列表使用数组来存储数据,因此您可以通过 LinkedList
的便利性来获得数组的速度优势,因为您可以添加和删除项目而不必担心手动 改变它的大小.
Lists use arrays to store the data so you get the speed benefit of arrays with the convenience of a LinkedList
by being able to add and remove items without worrying about having to manually change its size.
这并不意味着数组的大小(在这个例子中,一个 List
)没有改变 - 因此强调手动这个词.
This doesn't mean an array's size (in this instance, a List
) isn't changed though - hence the emphasis on the word manually.
一旦您的数组达到其预定义的大小,JIT 就会在堆上分配一个两倍大小的新数组,并复制现有数组.
As soon as your array hits its predefined size, the JIT will allocate a new array on the heap that is twice the size and copy your existing array across.
这篇关于更改数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!