You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中ArrayList的Capacity属性疑问:添加元素后容量变化原因解析

Why ArrayList Capacity Changed to 8 After Using AddRange?

Let's break down exactly what's happening with your ArrayList's capacity here—it all comes down to how ArrayList handles internal resizing in C#.

Step 1: Initial Capacity of listInt

When you created listInt and added 3 elements (9,10,11), the output showed Capacity Before: 4. That makes perfect sense because:

  • The default ArrayList starts with a capacity of 0. When you add the first element, it automatically resizes to a capacity of 4 (this is the default initial growth threshold for ArrayList).
  • Since you only added 3 elements, you didn't hit the capacity limit yet, so it stayed at 4.

Step 2: What Happens When You Call AddRange(list2)

You added 3 more elements from list2 to listInt, bringing the total number of elements to 6. Now the current capacity (4) can't hold all 6 elements, so ArrayList triggers a resize. Here's the core rule behind this:

If the required capacity exceeds the current capacity, the new capacity is set to the larger value between twice the current capacity or the exact required capacity.

In your scenario:

  • Current capacity: 4
  • Required capacity after adding 3 elements: 3 (existing) + 3 (new) = 6
  • Twice the current capacity is 8, which is larger than 6. So the capacity gets updated to 8.

Quick Test to Confirm the Logic

If you want to validate this further, try adding more elements to listInt after the AddRange call:

listInt.Add(12); // Total elements: 7, Capacity stays at 8
listInt.Add(13); // Total elements: 8, Capacity still 8
listInt.Add(14); // Total elements: 9, Capacity jumps to 16 (twice 8)

As a side note: ArrayList is a non-generic collection and is largely replaced by type-safe alternatives like List<T> (e.g., List<int> or List<string>) in modern C#. List<T> follows nearly identical resizing logic but avoids boxing/unboxing overhead and type errors.

内容的提问来源于stack exchange,提问作者Shailesh Prajapati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:30:59