.NET 中的 List 与 Java 中的 arraylist 的工作方式相同吗? [英] Does the List in .NET work the same way as arraylist in Java?

查看:27
本文介绍了.NET 中的 List 与 Java 中的 arraylist 的工作方式相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我学习 Java 时,有人告诉我数组列表是这样工作的:

When I learned Java, I was told that the arraylist works this way:

  • 它创建了一个可容纳 10 个元素的数组.

  • It creates an array with room for 10 elements.

添加第11个元素时,会创建一个新列表,其中有20个元素的空间,并将10个元素复制到新数组中.这将重复,直到没有更多元素要添加或达到最大尺寸为止.

When the 11th element is added, it is created a new list with room for 20 elements, and the 10 elements are copied into the new array. This will repeat as until there are no more elements to add, or to a maximum size.

.NET 中的 List 是用同样的方式构造的吗?

Is the List in .NET constructed the same way?

推荐答案

您可以通过查询 List 的 Capacity 轻松测试:

You can easily test this by querying a List's Capacity:

    var a = new List<string>();

    Console.WriteLine(a.Capacity); // Writes 0

    a.Add("abc");

    Console.WriteLine(a.Capacity); // Writes 4

    a.Add("abc");
    a.Add("abc");
    a.Add("abc");
    a.Add("abc");

    Console.WriteLine(a.Capacity); // Writes 8

所以它在实例化时根本不分配任何空间,而是在第一次添加项目时.从 8 增长到 16、32 等......

So it doesn't allocate any room at all upon instantiation, but upon first added item. From 8 it grows to 16, 32, etc...

这篇关于.NET 中的 List 与 Java 中的 arraylist 的工作方式相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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