Arrays in Apex are very similar to lists. Basically the only distinction is the syntax. The syntax of arrays is more traditional, like java. Below is an example of an array.

Index 0 − HCL
Index 1 − H2SO4
Index 2 − NACL
Index 3 − H2O
Index 4 − N2
Index 5 − U296

Below is the syntax for declaring an array.

<String> [] arrayOfProducts = new List<String>();

Below is a practical example of how an array can be used.

//Defining array
String [] arrayOfProducts = new List<String>();

//Adding elements in Array
arrayOfProducts.add('HCL');
arrayOfProducts.add('H2SO4');
arrayOfProducts.add('NACL');
arrayOfProducts.add('H2O');
arrayOfProducts.add('N2');
arrayOfProducts.add('U296');

for (Integer i = 0; i<arrayOfProducts.size(); i++) {
   //This loop will print all the elements in array
   system.debug('Values In Array: '+arrayOfProducts[i]);
}

The way it works is, firstly, the array is declared. Then elements are added (syntax is fairly simple). Then there is a for loop which iterates through the array and prints out a string with the product of the array for loop (i).

Below we have a means of accessing elements in an array. It is called an index.

//Accessing the element in array
//We would access the element at Index 3
System.debug('Value at Index 3 is :'+arrayOfProducts[3]);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s