简体   繁体   中英

Does the List in .NET work the same way as arraylist in Java?

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

  • It creates an array with room for 10 elements.

  • 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.

Is the List in .NET constructed the same way?

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

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

The generic List type doubles its internal array length every time the current array is filled up.

MSDN Link

细节有点不同(就元素的默认数量及其扩展方式而言),但基本上是相同的。

I believe that's how it works, yes. I can't find any documentation at the moment that tells you the exact algorithm they use, but there is definitely the concept of Capacity (size of the "internal" array) and Count (the actual number of elements you've added).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM