Tutorial: Arrays
Storing Information in memoryUsing Arrays in Quorum
Like many programming languages, Quorum has a variety of support classes for storing information in memory. In Quorum, these are generally called containers and in this tutorial, we will discuss how to use arrays.Adding to an Array
We can add to a array using code like the following:
//like with arrays, this code represents a template, a array that is filled only with integers
use Libraries.Containers.Array
Array<integer> array
//put a value in the second slot in the array, which is named 1
array:Add(5)
output "We added an item to the array."
Quorum does not allow us to add types to a templated value unless it matches exactly the type specified in the generic. So, for example, the following would be a compiler error:
use Libraries.Containers.Array
Array<integer> array
//since we have declared this array to use integers, we cannot put in a number type (with a decimal point)
array:Add(5.0)
Getting Items From a Array
Once we have added values to a array, we can obtain them individually using the Get action, like so:
use Libraries.Containers.Array
Array<integer> myList
//add two values to the array, 12 and 13
myList:Add(12)
myList:Add(13)
//this line returns the first integer, 12
integer value = myList:Get(0)
output value
Removing Items From a Array
Similarly to getting, we can remove items from a array. If we want to remove just the first version of a value (values are not guaranteed to be unique), then we can call Remove. If we want to remove all instances of an item, we can call RemoveAll. If an item is found, we are returned a boolean saying that the removal was successful.
use Libraries.Containers.Array
Array<integer> myList
myList:Add(43)
myList:Add(13)
myList:Add(43)
//RemoveAll(43) would remove all 43s
boolean removed = myList:Remove(43)
output removed
Iterating Over a Array
Finally, we often want to traverse over all elements in a array. To do this, we can use the Iterator class and ask it for each element, one at a time. The following example shows us how we might do this:
use Libraries.Containers.Array
use Libraries.Containers.Iterator
class Main
action Main
Array<integer> array
//add 3 items: 5, 10, and 15
array:Add(5)
array:Add(10)
array:Add(15)
//create an iterator to traverse our array
Iterator<integer> it = array:GetIterator()
//Keep iterating if more elements exist
repeat while it:HasNext()
//get the next item.
integer value = it:Next()
output value
end
end
end
Next Tutorial
In the next tutorial, we will discuss Containers, which describes how to use containers.