Lists
Lists are like arrays in that you can store several items of data of the same data type. But lists have an added benefit.. you can dynamically expand or contract by adding or deleting items. Stacks are a fixed size.
Step 1. Create the List
To create a list you must define the data type of the objects which will be stored. You must also allocate memory for the list structure. The list below has been created to store the simple data type int.
List<int> myNumbers = new List<int>();
Step 2: Add items
Use the add function to add a number.
Numbers.add(99);
You can even decide the position in which to store the object
myNumbers.add(0, 99);
Step 3: Retrieve an item
The following code will get the first object from the list.
int val = myNumbers.get(0);
Step 4: Loop through the entire list
The following code will get each item from myNumbers
and store into the local variable val
.
for (int x = 0; x < myNumbers.size(); x++)
{
int val = myNumbers.get(x);
// do something with val
}
An easier loop: foreach
The following code will retrieve each item in order and store it in val.
foreach (int val in myNumbers)
{
// do something with val
}