Valhalla Legends Forums Archive | Battle.net Bot Development | [VB] Code: Collection Class

AuthorMessageTime
CupHead
Spht was asking about Collection manipulation, and since I wasn't able to find an easy way to do so, I wrote this quick class as a means of merging Collection and array functionality. It worked as far as I tested it, and can easily be extended to include such Collection features as position insert and keys. Note that as soon as the collection is initialized, it will have one empty item. Similarly if you remove all items in the class, it will contain one empty item.

[code]
' File: cCollection.cls
' By: CupHead
' Purpose: Gives Collection functionality to an array.

Option Explicit
Option Base 1

Private TheArray() As Variant
Private TheCount As Long

Public Property Get Item(ByVal Index As Long) As Variant
Item = TheArray(Index)
End Property

Public Property Get Count() As Long
Count = UBound(TheArray)
End Property

Private Sub CleanArray()
Dim i As Integer
Dim TempArray() As String
Dim TempCount As Integer
TempCount = 1
ReDim TempArray(TempCount)

For i = LBound(TheArray) To UBound(TheArray)
If TheArray(i) <> vbNullString Then
TempArray(TempCount) = TheArray(i)
TempCount = TempCount + 1
ReDim Preserve TempArray(TempCount)
End If
Next i

ReDim TheArray(UBound(TempArray))
For i = LBound(TempArray) To UBound(TempArray)
TheArray(i) = TempArray(i)
Next i
End Sub

Public Sub Add(ByVal TheItem As Variant)
TheArray(TheCount) = TheItem
TheCount = TheCount + 1
ReDim Preserve TheArray(TheCount)
End Sub

Public Sub Remove(ByVal Index As Long)
If Index < 1 Or Index > TheCount - 1 Then Exit Sub
TheArray(Index) = vbNullString
Call CleanArray
End Sub

Public Sub SetItem(ByVal Index As Long, ByVal Value As Variant)
If Index < 1 Or Index > TheCount - 1 Then Exit Sub
TheArray(Index) = Value
End Sub

Private Sub Class_Initialize()
TheCount = 1
ReDim TheArray(TheCount)
End Sub
[/code]
April 12, 2003, 11:41 PM
TheMinistered
That would be much slower than the intristic collection class provided, if you want a good example i suggest that you use the class builder add-in provided by mircosoft.
April 13, 2003, 2:06 PM
CupHead
Dword, if you hadn't noticed, the collection class provided has limited functionality and room for improvement, particularly in item manipulation while they exist in the collection. Somehow I doubt you went and ran benchmarks on the code to see how much the speed varies. ;) I, on the other hand, did.

Overall, the class I wrote runs about 11x slower. (100000 items took 1.4 seconds with my class as opposed to .12 seconds with the intrinsic collection class.) However, manipulating an item to a desired position (without keys) in the collection took much longer than the .031 seconds it took my class to modify an array item. So it's tradeoff, ease of manipulation of the items vs. the speed of VB's collection class.
April 14, 2003, 5:18 PM

Search