You are on page 1of 28

Pemrograman Lanjut

Array, Collection, and Iterator

Victor Phoa, S.Si., M.Cs - @2020


Array Definition
• An array is a data structure, which can store a fixed-size collection of
elements of the same data type.

• An array is used to store a collection of data, but it is often more useful to


think of an array as a collection of variables of the same type.

• Instead of declaring many individual variables, such as number1,


number2, ..., number99, just declare one array variable number of integer
type and use number1[0], number1[1], and .. , number1[99].

• Number 0, 1, 2, ... 99 are index associated with var variable and they are
being used to represent individual elements available in the array.
Array Access and Structure

• All arrays consist of contiguous memory locations. The


lowest address corresponds to the first element and the
highest address to the last element.
Declaring Array in C#

• To declare an array in C#, you can use the following


syntax

datatype[] arrayName;

• For Example:

int[] matrix;

string[] nameList;
Initialize Arrays in C#

• You can assign values to individual array elements, by


using the index number, for example:
double[] balance = new double[10];
balance[0] = 4500.0;
balance[1] = 4523.69;
balance[2] = 3421.0;
• Or at declaration:
double[] balance = { 2340.0, 4523.69, 3421.0};
• Other example:
int [] marks = new int[5] { 99, 98, 92, 97, 95};
Accessing Array Elements

• An element is accessed by indexing the array name. This


is done by placing the index of the element within square
brackets after the name of the array. For example:

double salary = balance[9];


Demo Example
static void Main(string[] args) {
int [] n = new int[10]; /* n is an array of 10 integers */
int i,j;

/* initialize elements of array n */


for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100;
}

/* output each array element's value */


for (j = 0; j < 10; j++ ) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
}
Demo Output
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Multidimensional Arrays

• C# allows multidimensional arrays.

• Multi-dimensional arrays are also called rectangular array.


You can declare a 2-dimensional array of strings as:

string [,] names;

• or, a 3-dimensional array of int variables as


int [ , , ] matrixArray;
Two-Dimensional Arrays

• The simplest form of the multidimensional array is the 2-


dimensional array. A 2-dimensional array is a list of one-
dimensional arrays.
Initializing Two-Dimensional Arrays

• Multidimensional arrays may be initialized by specifying


bracketed values for each row. The Following array is with
3 rows and each row has 4 columns.
int [,] a = new int [3,4] {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

• Array is accessed by using the subscripts. That is, row


index and column index of the array. For example:
int val = a[2,3];
Demo Example
static void Main(string[] args) {
/* an array with 5 rows and 2 columns*/
int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
int i, j;

/* output each array element's value */


for (i = 0; i < 5; i++) {

for (j = 0; j < 2; j++) {


Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
}
}
Console.ReadKey();
}
Demo Output
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8
Collection

• There are two ways to group objects: by creating arrays of objects,


and by creating collections of objects.

• Arrays are most useful for creating and working with a fixed
number of strongly-typed objects.

• Collections provide a more flexible way to work with groups of


objects.

• Unlike arrays, the group of objects you work with can grow and
shrink dynamically as the needs of the application change.
Collection (cont.)

• Collection classes are specialized classes for data storage and


retrieval.

• These classes provide support for stacks, queues, lists, and hash
tables.

• Most collection classes implement the same interfaces.

• For some collections, you can assign a key to any object that you
put into the collection so that you can quickly retrieve the object by
using the key.
Various Collection Classes and Their Usage (1)

• The following are the various commonly used classes of


the System.Collection namespace :

• ArrayList:
– It represents ordered collection of an object that can be indexed
individually.
– It is basically an alternative to an array. However, unlike array
you can add and remove items from a list at a specified position
Various Collection Classes and Their Usage (2)

• Hashtable:
– It uses a key to access the elements in the collection.
– A hash table is used when you need to access
elements by using key, and you can identify a useful
key value.
– Each item in the hash table has a key/value pair.
Various Collection Classes and Their Usage (3)

• SortedList:
– It uses a key as well as an index to access the items in a list.
– The collection of items is always sorted by the key value.

• Stack:
– It represents a last-in, first out collection of object.
– When you add an item in the list, it is called pushing the item
– When you remove it, it is called popping the item.
Various Collection Classes and Their Usage (4)

• Queue:
– It represents a first-in, first out collection of object.
– When you add an item in the list, it is called enqueue
– When you remove an item, it is called deque.

• BitArray:
– It represents an array of the binary representation using the
values 1 and 0.
– You can access items from the BitArray collection by using an
integer index, which starts from zero.
Collection
• The System.Collections namespace includes the interfaces and classes for
the non-generic collections.
• The following diagram illustrates the hierarchy of the interfaces and classes
for the non-generic collections.
Collection<T> Class

• Collection<T> Class provides the base class for a generic


collection.

• Notable Properties:
– Count : Gets the number of elements actually contained in the
Collection<T>
– Item[Int32]: Gets or sets the element at the specified index.
– Items: Gets a IList<T> wrapper around the Collection<T>
• Notable Methods:
– Add(T), Clear(), ClearItems(), Contains(T), IndexOf(T), Insert(Int32, T),
Remove(T), RemoveAt(Int32), RemoveItem(Int32), SetItem(Int32, T).
Collection Usage Example
Collection<string> dinosaurs = new Collection<string>();
dinosaurs.Add("Psitticosaurus");
dinosaurs.Add("Caudipteryx");
dinosaurs.Add("Compsognathus");
dinosaurs.Add("Muttaburrasaurus");

Console.WriteLine("{0} dinosaurs:", dinosaurs.Count);


Console.WriteLine("\nIndexOf(\"Muttaburrasaurus\"): {0}",
dinosaurs.IndexOf("Muttaburrasaurus"));
Console.WriteLine("\nContains(\"Caudipteryx\"): {0}",
dinosaurs.Contains("Caudipteryx"));

dinosaurs.Insert(2, "Caudipteryx");

dinosaurs.Remove("Microraptor");

dinosaurs.RemoveAt(0);

dinosaurs.Clear();
ArrayList

• ArrayList Class implements the IList interface using an array


whose size is dynamically increased as required.

• Notable Properties:
– Capacity, Count, Item[Int32]

• Notable Methods:
– Add(Object), AddRange(ICollection), BinarySearch(Object), Clear(),
Contains(Object), Equals(Object), IndexOf(Object, Int32), Insert(Int32,
Object), InsertRange(Int32, ICollection), Remove(Object),
RemoveAt(Int32), Sort(Comparer), Reverse()
ArrayList Example
using System;
using System.Collections;
public class SamplesArrayList {

public static void Main() {

// Creates and initializes a new ArrayList.


ArrayList myAL = new ArrayList();
myAL.Add("Hello");
myAL.Add("World");
myAL.Add("!");

// Displays the properties and values of the ArrayList.


Console.WriteLine( "myAL" );
Console.WriteLine( " Count: {0}", myAL.Count );
Console.WriteLine( " Capacity: {0}", myAL.Capacity );
Console.Write( " Values:" );
PrintValues( myAL );
}

public static void PrintValues( IEnumerable myList ) {


foreach ( Object obj in myList )
Console.Write( " {0}", obj );
Console.WriteLine();
}
}
ArrayList Example Output

myAL
Count: 3
Capacity: 4
Values: Hello World !
Iterators

• An iterator can be used to step through collections such


as lists and arrays.

• An iterator is a method in C# to retrieve elements one by


one.

• Or in other words, we can say that an iterator is used to


perform an iteration over the collections.
Classic Iteration vs Foreach Iterator

• Using For Statement


//array: for next //collection: for next
for (int i = 0; i<25; i++){ for (int i = 0; i<25; i++){
boxArray[i].RandomColor(); boxCollection[i].RandomColor();
} }

• Using Foreach Statement


//array: foreach //collection: foreach
foreach (var box in boxArray){ foreach (var box in boxCollection){
box.RandomColor(); box.RandomColor();
} }
Tugas

• 1. Modifikasi Source Code 2 pada BKPM 5.


• 2. Ganti Penggunaan Collection menjadi ArrayList.
• 3. Tugas dikumpulkan pada kelas Tatap Muka.

You might also like