ArrayList与Array中的元素分配方式如何?

huangapple go评论66阅读模式
英文:

How are elements allocated in ArrayList vs Array?

问题

根据我正在阅读的书中,

> 数组列表的容量和数组的大小之间有一个重要区别。如果你分配了一个包含100个条目的数组,
那么这个数组有100个插槽,可以使用。一个具有100个元素容量的数组列表有可能容纳100个元素
(实际上,还可以容纳超过100个元素,但会增加额外的重新分配成本)—
但在开始时,甚至在初始构造之后,数组列表不包含任何元素。

然而,我们也可以创建一个没有定义任何容量的数组列表。

没有定义任何容量的数组列表以及具有容量的数组列表将如何分配其元素,
以及我们何时应该使用其中之一?

我脑海中唯一浮现的是,既然两种方式(具有容量的数组列表和没有容量的数组列表)中的值都会以相同的方式处理,
那么为什么我们需要容量呢?因此我能想到的唯一可能原因是它们两者以不同的方式保存值。

英文:

According to a book I was reading

> There is an important distinction between the capacity of an array list
and the size of an array. If you allocate an array with 100 entries,
then the array has 100 slots, ready for use. An array list with a
capacity of 100 elements has the potential of holding 100 elements
(and, in fact, more than 100, at the cost of additional reallocations)—
but at the beginning, even after its initial construction, an array list
holds no elements at all.

However, we can also create an ArrayList without any capacity defined.

How will an ArrayList without any capacity defined and an ArrayList with capacity allocate its elements and when we should use one over the other?

The only thing striking my mind is, why would we have capacity if in both ways (ArrayList with capacity and ArrayList with no capacity), the values will be treated same way, so the only possible reason coming in my mind is that they both hold values differently.

答案1

得分: 0

提供初始分配的原因是为了预先分配所需的内存表示,以容纳那么多项目,否则需要为所有添加的项目进行动态分配。注意,一旦数组包含预分配项目的数量,动态分配就变得必要。

英文:

The reason for providing an initial allocation is to pre-allocate the memory representation required to hold that many items, otherwise dynamic allocation is necessary for all item added. Note, dynamic allocation becomes necessary once the array contains the number of pre-allocated items.

huangapple
  • 本文由 发表于 2020年10月5日 21:23:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64209484.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定