为什么“列表容量"调整为远远超出所需的大小? [英] Why does List Capacity resize to much more than is needed?

查看:40
本文介绍了为什么“列表容量"调整为远远超出所需的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用10000个随机整数填充列表,范围为0到20000.这是我的代码:

I'm trying to fill a list with 10000 random integers in the range of 0 to 20000. Here is the code for how I do it:

List<int> rand_num = new List<int>();
        Random rand = new Random();
        int i =0;
        //int counter = 0;
        while (i < 10000)
        {
            rand_num.Add(rand.Next(0, 20000));
            i++;
        }

        textBox1.Text = rand_num.Capacity.ToString();

问题是当它到达textBox1.Text = rand_num.Capacity.ToString();行时,输出为16384.我只输入了10000个数字,如何将其大小调整为6384,超出我的需要?我是否缺少有关列表在c#中的行为的信息?

The problem is when it gets to the textBox1.Text = rand_num.Capacity.ToString(); line, the output is 16384. I have only entered 10000 numbers, how can it re size to 6384 more than what I need? Am I missing something about how lists behave in c#?

推荐答案

Capacity 是列表 可以容纳多少,然后需要对其内部进行调整.

Capacity is how much the list can hold, before it needs to be resized internally.

容量始终大于或等于Count.如果计数超过 容量增加元素时,容量增加 复制旧版本之前自动重新分配内部数组 元素并添加新元素.

Capacity is always greater than or equal to Count. If Count exceeds Capacity while adding elements, the capacity is increased by automatically reallocating the internal array before copying the old elements and adding the new elements.

您正在寻找的是 Count ,它返回列表中当前中的元素数量.

What you are looking for is Count, which returns the amount of elements currently in the list.

textBox1.Text = rand_num.Count.ToString();

当元素的数量需要超过容量时,.NET将调整内部数组的大小,使其可以容纳更多的值,这通常是一项昂贵的操作.如果您事先知道所需的最大数量值,也可以设置Capacity属性.

When the number of elements needs to become more than the capacity, .NET will resize the internal array so it can hold more values, which is generally an expensive operation. The Capacity property can also be set if you know in advance the maximum amount of values you will need.

这篇关于为什么“列表容量"调整为远远超出所需的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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