The class Collection (gb) implements a hash table whose elements consist of a value-key pair.
Properties of the class Collection:
Property | Data type | Description |
---|---|---|
Count | Integer | Returns the number of items stored in a collection. |
Length | Integer | Returns the number of items stored in a collection. Count and length are used synonymously. |
Key | String | Returns the key of the last read or enumerated element in a collection. |
Table 7.5.0.1.1.1: Class Collection properties
The Collection class has the following methods:
Method | Return type | Description |
---|---|---|
Add (Value As Variant, Key As String) | - | Inserts an element - consisting of a value and a key - into a collection. |
Clear () | - | Deletes the contents of a collection. |
Copy () As Collection | Collection | This function returns a 1:1 copy of the original collection. |
Exist (Key As String) As Boolean | Boolean | The function returns True if there is a value bound to this key for the given key. |
Remove (Key As String) | - | Removes the element with the specified key Key from a collection - if the element exists, which can be checked securely with the Collection. Exist (Key) method. |
Table 7.5.0.2.1: Methods of the Collection class
There are different ways to create a collection:
(A) declaration of a variable of the data type collection and subsequent assignment of the element
(B) declaration of a variable of the data type collection with direct value assignment
(C) inline collection create
(D) copy of a collection
The following examples implement the options listed in the previous chapter.
(A) declaration of a variable of the data type collection and subsequent assignment of elements
Dim hCollection As Collection hCollection = New Collection ( [ Mode As Integer ] )
A new collection is created. Specifying mode is optional. The gb.binary mode is the default. The mode describes the method used for comparing keys and applies using the two gambas constants:
gb.Binary: This constant represents 0 and indicates that capitalization is case-sensitive. gb.IgnoreCase: This constant represents 1 --> upper and lower case is ignored.
Example 1
Public Sub btnAddMethod_Click() Dim cCollection As New Collection(gb.IgnoreCase) Dim vValue, vElement As Variant Dim aNames As String[] Dim icount As Integer aNames = ["Adam", "Ben", "Charlie"] ' cCollection.Add(Value As Variant, Key As String) → First the value and then the key cCollection.Add("a", "a") cCollection.Add(3, "A") cCollection.Add(aNames, "v") ' The value is a string array cCollection.Add(False, "d") cCollection.Add(8.44, "e") cCollection.Add(Format(Date(Now), "d. mmmm yyyy"), "f") For Each vValue In cCollection If cCollection.Key = "v" Then For iCount = 0 To vValue.Max Print cCollection.Key & (icount + 1); " --> "; vValue[iCount] Next ' iCount Else Print cCollection.Key; " --> "; vValue Endif ' cCollection.Key = "v" ? Next ' vValue End ' btnAddMethod_Click()
The output in the console of the Gambas IDE also demonstrates how to read the values associated with the key:
a --> 3 v1 --> Adam v2 --> Ben v3 --> Charlie d --> False e --> 8,44 f --> 7. April 2014
The capitalization of the key is ignored in this mode. The first element is therefore overwritten. The key “A” becomes “a” with the value 3, because two values are noted for the same key.
This also provides a clear answer to the question “Can you use different data types for the values in a collection?”:“ Yes - each value of a collection is of the type Variant and a variant can carry everything - independent of the collection and independent of the other values in a collection”.
Example 2
In example 1, you could also assign the values to the keys in this way:
' cCollection[Key As String] = Value As Variant → First the key and then the value cCollection["a"] = "a" cCollection["A"] = "3" cCollection["v"] = aNames ' The value is a string array cCollection["d"] = False cCollection["e"] = 8.44 cCollection["f"] = Format(Date(Now), "d. mmmm yyyy")
Hint:
The !-operator is a special operator for container objects that allow access to their elements using a' String' type key –> chapter 8.6. A collection is also included. The key string is written after the !-operator, so that for example cCollection! name is synonymous with cCollection[“Name”]. Note that the quotation marks around the key string are omitted when using the !-operator. In both cases, the return value is the value in the collection with the key “Name”.
sCurrent.Name = cCollection["Name"] sCurrent.Name = cCollection!Name ' Alternative notation
(B) Inline Collection
Since revision #1699 (November 2008) there is a new syntax for creating a collection in Gambas. With this compact inline syntax, the key is noted first and then the value:
Dim cNames As New Collection Dim vValue, vElement As Variant ' Syntax: Collection = [ Key: Expression [ , ... ] ] cNames = ["w": ["Anna", "Brit", "Claudia", "Doreen"], "m": ["Adam", "Bruno", "Clemens"], "Surname": ["Eagle", "Fox", "Cat", "Weasel", "Zebra"]] ' Output to the Gambas IDE console For Each vValue In cNames For Each vElement In cNames[cNames.Key] Print cNames.Key; " -> "; vElement Next ' vElement Next ' vValue
(C) Declaration of a variable of the data type collection with direct value assignment.
This variant uses the inline syntax:
Dim cCollection As Collection = ["Blue": &H0000FF&, "White": &HFFFFFF&, "Red": &HFF0000&]
(D) Copy of a collection
When you create a copy of an existing collection using the Collection. Copy () method, this copy is a standalone collection object:
Dim cNames, cNamesCopy As New Collection cNames = ["w": ["Anna", "Brit"], "m": ["Adam", "Bruno"], "Surename": ["Eagle", "Cat"]] cNames["Surename"].Add("Mouse", 1) ' Insert after the Eagle (Index = 0)... cNames.Name = "cNAME" If cNames.Count > 0 Then cNamesCopy = cNames.Copy() Else ' Count = 0 Message.Error(„The Collection '” & cNames.Name & „' has no elements”) Endif ' cNames.Count > 0
The statement cNames.Name = “cNAME” is described in –> section 7.5.0.7.
You can access individual values of a collection, which requires precise knowledge of the key or all values:
Dim cColour As New Collection Dim vValue As Variant cColour.Add("&HC3DDFF", "TColour") cColour.Add("&HD6D4D2", "HColour") cColour.Add("&HF5FFE6", "EColour") Print "The background colour is "; cColour["HColour"] ' Displaying an element ' Print "The background colour is "; cColour!HColour → Alternative For Each vValue In cColor Print cColor.Key, String.Chr(187), vValue ' Show all elements (key value pairs) Next ' vValue
A gambas-specific memory management is used, with which you can save a collection in a file (data export) or import the contents of a file into a collection (data import). Further information can be found in chapter 7.2.2.2.3 Data export and data import.
Data export
The following procedure saves a collection in a binary, gambas-specific file:
Parameter1: File path to the export file
Parameter2: Reference to the selected collection
Public hFile As File Public sFilePath As String = Application.Path &/ "url.list" Public cData As New Collection Public Sub Form_Open() ... If Exist(sFilePath) Then cData = ImportCData(sFilePath) For Each vValue In cData lsbURL.Add(cData.Key) Next Else cData["http://mp3channels.webradio.rockantenne.de/classic-perlen"] = "ROCK ANTENNA" lsbURL.Add("http://mp3channels.webradio.rockantenne.de/classic-perlen") Endif ' Exist(sFilePath) ? End ' Form_Open() Public Sub ExportCData(sPath As String, cExport As Collection) If cExport.Count = 0 Then Return Else hFile = Open sPath For Write Create ' The export file is always created anew Write #hFile, cExport As Collection Close #hFile Catch Message.Error("The data export was incorrect!" & gb.NewLine & "ERROR: " & Error.Text) Endif ' c.Count = 0 ? End ' ExportCData(...)
This function imports the contents of a collection from a binary, gambas-specific file and returns a collection as a function value:
Parameter: File path to import file
Public Function ImportCData(sPath As String) As Collection Dim cTempImport As Collection hFile = Open sPath For Read cTempImport = Read #hFile As Collection Close #hFile Return cTempImport Catch Message.Error("The data import was incorrect!" & gb.NewLine & "ERROR: " & Error.Text) End ' ImportCData(...)
If you want a collection to have a name - which it does not have - then expand the collection class by adding a class' Collection. class' to your project, exporting it and then adding the new' Name' property to the Collection class - the original class will be extended. Here follows the content of the newly created class file' Collection. class':
' Gambas class file Export Property Name As String Private $sName As String Private Sub Name_Read() As String Return $sName End Private Sub Name_Write(Value As String) $sName = Value End
Now you can assign an object name to each collection in your project and query it in the program. This is the only way to provide informative messages of the following type:
Dim cURL As New Collection cURL.Name = "TX_URL" If cURL.Count = 0 Then Message.Warning("The collection '" & cURL.Name & "' exist, but is empty!") Endif ' cURL.Count = 0 ?
Details on extending or changing classes can be found in chapter 26? classes, modules and libraries.