ArrayList vs List<> in C#

2018-12-31 07:51发布

What is the difference between ArrayList and List<> in C#?

Is it only that List<> has a type while ArrayList doesn't?

11条回答
无色无味的生活
2楼-- · 2018-12-31 08:05

I think, the differences between ArrayList and List<T> are:

  1. List<T>, where T is value-type is faster than ArrayList. This is because List<T> avoids boxing/unboxing (where T is value-type).
  2. Many sources say - usually ArrayList used just for backward compatibility. (is not a real difference, but i think it is important note).
  3. Reflection is easier with nongeneric ArrayList then List<T>
  4. ArrayList has IsSynchronized property. So, It is easy to create and use syncronised ArrayList. I didin't found IsSynchronized property for List<T>. Also Keep in mind this type of synchronization is relatively inefficient, msdn):

    var arraylist = new ArrayList();
    var arrayListSyncronized = ArrayList.Synchronized(arraylist
    Console.WriteLine($"syncronized {arraylist.IsSynchronized}");
    Console.WriteLine($"syncronized {arrayListSyncronized.IsSynchronized}");
    
    var list = new List<object>();
    var listSyncronized = ArrayList.Synchronized(list);
    Console.WriteLine($"syncronized {list.IsSynchronized}");//error, no such prop
    Console.WriteLine($"syncronized {list.IsSynchronized}");//error, no such prop
    
  5. ArrayList has ArrayList.SyncRoot property which can be used for syncronisation (msdn). List<T> hasn't SyncRoot property, so in the following construction you need to use some object if you use List<T>:

    ArrayList myCollection = new ArrayList();
    lock(myCollection.SyncRoot) //  ofcourse you can use another object for this goal
    {
        foreach (object item in myCollection)
        {
            // ...
        }
    }
    
查看更多
爱死公子算了
3楼-- · 2018-12-31 08:07

Using List<T> you can prevent casting errors. It is very useful to avoid a runtime casting error.

Example:

Here (using ArrayList) you can compile this code but you will see an execution error later.

ArrayList array1 = new ArrayList();
array1.Add(1);
array1.Add("Pony"); //No error at compile process
int total = 0;
foreach (int num in array1)
{
 total += num; //-->Runtime Error
}

If you use List, you avoid these errors:

List<int> list1 = new List<int>();
list1.Add(1);
//list1.Add("Pony"); //<-- Error at compile process
int total = 0;
foreach (int num in list1 )
{
 total += num;
}

Reference: MSDN

查看更多
何处买醉
4楼-- · 2018-12-31 08:07

To add to the above points. Using ArrayList in 64bit operating system takes 2x memory than using in the 32bit operating system. Meanwhile, generic list List<T> will use much low memory than the ArrayList.

for example if we use a ArrayList of 19MB in 32-bit it would take 39MB in the 64-bit. But if you have a generic list List<int> of 8MB in 32-bit it would take only 8.1MB in 64-bit, which is a whooping 481% difference when compared to ArrayList.

Source: ArrayList’s vs. generic List for primitive types and 64-bits

查看更多
十年一品温如言
5楼-- · 2018-12-31 08:15

Yes, pretty much. List<T> is a generic class. It supports storing values of a specific type without casting to or from object (which would have incurred boxing/unboxing overhead when T is a value type in the ArrayList case). ArrayList simply stores object references. As a generic collection, List<T> implements the generic IEnumerable<T> interface and can be used easily in LINQ (without requiring any Cast or OfType call).

ArrayList belongs to the days that C# didn't have generics. It's deprecated in favor of List<T>. You shouldn't use ArrayList in new code that targets .NET >= 2.0 unless you have to interface with an old API that uses it.

查看更多
梦寄多情
6楼-- · 2018-12-31 08:17

Another difference to add is with respect to Thread Synchronization.

ArrayList provides some thread-safety through the Synchronized property, which returns a thread-safe wrapper around the collection. The wrapper works by locking the entire collection on every add or remove operation. Therefore, each thread that is attempting to access the collection must wait for its turn to take the one lock. This is not scalable and can cause significant performance degradation for large collections.

List<T> does not provide any thread synchronization; user code must provide all synchronization when items are added or removed on multiple threads concurrently.

More info here Thread Synchronization in the .Net Framework

查看更多
无与为乐者.
7楼-- · 2018-12-31 08:17

Using "List" you can prevent casting errors. It is very useful to avoid a runtime casting error.

Example:

Here (using ArrayList) you can compile this code but you will see an execution error later.

    // Create a new ArrayList


    System.Collections.ArrayList mixedList = new System.Collections.ArrayList();


    // Add some numbers to the list
    mixedList.Add(7);
    mixedList.Add(21);


    // Add some strings to the list
    mixedList.Add("Hello");
    mixedList.Add("This is going to be a problem");




    System.Collections.ArrayList intList = new System.Collections.ArrayList();
    System.Collections.ArrayList strList = new System.Collections.ArrayList();


    foreach (object obj in mixedList)
    {
        if (obj.GetType().Equals(typeof(int)))
        {
            intList.Add(obj);
        }
        else if (obj.GetType().Equals(typeof(string)))
        {
            strList.Add(obj);
        }
        else
        {
            // error.
        }
    }
查看更多
登录 后发表回答