Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arraylist uses Array?

Does an ArrayList internally use an Array? Is this an empty array if we use the default constructor (new ArrayList())? Thanks.

like image 490
rkrauter Avatar asked Dec 18 '22 01:12

rkrauter


2 Answers

Yes it does. One of the easiest ways to verify this is to look at the source. You can either get your hands on the reference source, or you can simply use .NET Reflector to decompile the .NET DLLs.

Here's the relevant part of ArrayList, from Reflector:

public class ArrayList : IList, ICollection, IEnumerable, ICloneable
{
    static ArrayList()
    {
        emptyArray = new object[0];
    }

    public ArrayList()
    {
        this._items = emptyArray;
    }

    private object[] _items;

    private static readonly object[] emptyArray;

    // etc...
}

You shouldn't rely on this always being the case. It is an implementation detail and could change in future versions of .NET (although it probably won't). Also for new code you should consider using List<T> instead of ArrayList.

like image 111
Mark Byers Avatar answered Jan 02 '23 08:01

Mark Byers


Yes, an ArrayList uses an array to store the items.

If you create an ArrayList without specifying a capacity, the default starting capacity is used. What the default starting capacity is may depend on the version of the framework. For framework 2 it seems to be zero. In framework 1 i think that it was 16.

like image 38
Guffa Avatar answered Jan 02 '23 07:01

Guffa