HTML clipboardThe ArrayList class implements a collection of objects using an array whose size
is dynamically increased as required. The ArrayList class is very useful if you
are working with arrays and need to add, remove, index, or search for data in a
collection.
Although ArrayList is very versatile and grows dynamically when you add values,
it is slower than the Array class, which allows you to access its members with
subscripts but does not let the array grow during runtime. When choosing between
Array and ArrayList, decide which feature is important to your application. To
get a better idea of how an Array compares to an ArrayList, think of an
ArrayList as nothing more than a linked-list implementation of an Array. Adding
data to an ArrayList is pretty easy; just call the class's Add member, as shown
in below example.
Example of Adding an element to an ArrayList
Imports
System.Collections.Generic
Imports
System.Linq
Imports
System.Text
Imports
System.Collections
Namespace systemArrayListClass
Class Program
Shared Sub
Main(ByVal
args As String())
Dim dataArray As New ArrayList()
For i As Integer
= 0 To
19
dataArray.Add(i)
Next
' or you can add any object type like below.
dataArray.Add("Object
type")
End Sub
End Class
End Namespace
You can also insert an element into the ArrayList at a specified index. Note
that if you specify the index item as the last item + 1, the Insert method works
the same way as the Add method:
myList.Insert(1,
"real first")
The Remove and RemoveAt members delete data from an ArrayList. The RemoveAt
method removes the element at the specified index of the ArrayList, while the
Remove method removes the first occurrence of a specific object from the
ArrayList:
myList.Remove("3")
// Remove the
element containing "3".
The BinarySearch member of ArrayList is very useful and fast for searching for
elements. This member returns the zero-based index of a specific element in the
sorted ArrayList or a portion of it using a binary search algorithm:
Dim
myIndex As Integer
= myList.BinarySearch(3)
With the ToArray function, you can copy the elements of the ArrayList to a new
array of the specified type:
Dim
myIntArr As Integer()
= myList.ToArray(Int32)
You can always set the capacity to the actual number of elements in the
ArrayList with the TrimToSize function:
myList.TrimToSize()
Conclusion
Hope this article would have helped you in understanding the System.ArrayList
Class using VB.NET.