Don't use ArrayList!

不想你离开。 提交于 2019-12-19 18:58:14

问题


People often tell me not to use ArrayList for making my arrays in VB.NET. I would like to hear opinions about that, why shouldn't I? What is the best method for creating and manipulating array contents, dimensions etc?

Thanks.


回答1:


Use generic lists instead. ArrayList is not typed, meaning that you can have a list with strings, numbers, +++. Rather you should use a generic list like this:

Dim list1 As New List(Of String) ' This beeing a list of string

The lists-class also allows you to expand the list on the fly, however, it also enforces typing which helps write cleaner code (you don't have to typecast) and code that is less prone to bugs.

ArrayList is gennerally speaking just a List(Of Object).




回答2:


ArrayLists are not type checked so you will need to do a lot of boxing/unboxing. Use a .net collection instead that support generics like List.

Because List does not have to unbox your objects it boasts a surprisingly better performance than Arraylist.




回答3:


ArrayLists are less performant and memory-extensive:

Dim list1 As New ArrayList
For i As Integer = 1 To 100000000
    list1.Add(i)
Next
' --> OutOfMemoryException after 13.163 seconds, having added 67.108.864 items

Dim list2 As New List(Of Integer)
For i As Integer = 1 To 100000000
    list2.Add(i)
Next
' --> finished after 1.778 seconds, having added all values



回答4:


Because its not strongly typed. Use a List(Of T) which T is your type.



来源:https://stackoverflow.com/questions/4823684/dont-use-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!