.NET: ArrayList vs List

后端 未结 5 1448
别跟我提以往
别跟我提以往 2020-12-08 19:25

What is the difference between ArrayList and List in VB.NET

相关标签:
5条回答
  • 2020-12-08 19:33

    List can make use of generics so that only objects of specific types can be placed into it, so that you can have extra type checking and so that you can cut down on processing time due to boxing and unboxing. Arraylist cannot use this. In almost all cases, you'll want to use a List rather than an Arraylist.

    0 讨论(0)
  • 2020-12-08 19:38

    List is a generic implementation of ArrayList. ArrayList stores all objects as System.Object which you need then cast to appropriate type. ArrayLists are heterogenous, List can store only one type of objects - that type supplied as its generic parameter.

    List<string> strList; // can store only strings
    List<int> intList; // can store only ints
    ArrayList someList; // can store anything
    
    0 讨论(0)
  • 2020-12-08 19:49

    ArrayLists are essentially deprecated as they're untyped - you need to use casts with them - and they're slower and less space efficient for value types because they require the items to be boxed.

    Generic lists were introduced with .Net 2.0 and are the way to go. Often a List is better than an array, with few downsides.

    As these collections are part of the .Net Base Class Library, this advice also applies to C# and to any .Net language which supports generics - it's not specific to VB.NET.

    0 讨论(0)
  • 2020-12-08 19:53

    ArrayList allows you to write this:

    Dim customers as new ArrayList
    Dim c as new Customer
    Dim m as new Manager
    customers.Add(c)
    customers.Add(m)
    
    'This will cause an exception '  
    For each c as Customer in customers
    console.writeline(c.Name)
    Next
    

    A List(of Customer) allows only object of Customer type and types that inherit from Customer, so you cannot make such mistakes.

    Even if you need to put objects of unrelated types in the same collection, a List(Of Object) is a better choice as it makes explicit that you are dealing with different types.

    0 讨论(0)
  • 2020-12-08 19:56

    ArrayLists are even more space inefficient when used on 64bit to store primitive elements because of the 64bit wide memory references as opposed to 32bit references on 32bit machines, and boxing.

    See this for more details: http://blogs.msdn.com/joshwil/archive/2004/04/13/112598.aspx

    0 讨论(0)
提交回复
热议问题