为什么在提供建设足够的大小列表插入失败? [英] Why does list insertion fail when sufficient size is provided on construction?

查看:209
本文介绍了为什么在提供建设足够的大小列表插入失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有如下的变量声明:

If we have the following variable declaration:

List<int> list = new List(5);



为什么这样的:

Why does this:

list.insert(2, 3);



失败,出现以下错误:

fail with the following error:

Index must be within the bounds of the List.



什么是提供初始大小的点?

What's the point of providing the initial size?

推荐答案

所有的初始大小确实是提供的提示,实现至少有一个给定的容量。它不创造充满 N 默认项的列表;重点煤矿:

All the initial size does is provide a hint to the implementation to have at least a given capacity. It does not create a list filled with N default entries; emphasis mine:

初始化列表℃的新实例; T> 类< STRONG>是空并具有指定的初始容量。

Initializes a new instance of the List<T> class that is empty and has the specified initial capacity.

如果您继续通过MSDN进入备注部分,你会发现为什么这提供构造函数重载(再次,重点煤矿):

If you continue through the MSDN entry to the Remarks section, you'll find why this constructor overload is provided (again, emphasis mine):

的能力清单< T> 是,名单,LT元素的数量; T> 可以持有。因为元素被添加到列表< T> ,容量自动增加的要求重新分配内部数组

The capacity of a List<T> is the number of elements that the List<T> can hold. As elements are added to a List<T>, the capacity is automatically increased as required by reallocating the internal array.

如果集合的大小可以估计,指定初始容量的消除了执行大量的大小调整操作的需要,同时将元素添加到列表< T> code>

If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the List<T>.

列表与LT>总之是不一样的列表< T> .Capacity (如果计数超过容量的同时,添加元素,容量的增加...)

In short List<T>.Count is not the same as List<T>.Capacity ("If Count exceeds Capacity while adding elements, the capacity is increased...").

您收到异常,因为仅列出的逻辑的包含您添加的项目,改变了容量不改变项目数逻辑的存储。如果你要设置列表< T> .Capacity 小于列表< T> .Count之间我们可以测试这个行为去另一个方向:

You receive the exception because the list only logically contains the items you add, changing the capacity does not change the number of items logically stored. If you were to set List<T>.Capacity to less than List<T>.Count we can test this behavior going the other direction:

Unhandled Exception: System.ArgumentOutOfRangeException: capacity was less than
 the current size.
Parameter name: value
   at System.Collections.Generic.List`1.set_Capacity(Int32 value)

要或者创建你要找的行为:

To perhaps create the behavior you're looking for:

public static List<T> CreateDefaultList<T>(int entries)
{
    return new List<T>(new T[entries]);
}

这篇关于为什么在提供建设足够的大小列表插入失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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