Apex Arrays

10 minute read
0
Arrays in Apex

Apex Arrays are the collection of similar elements, where the memory is allocated sequently. Each element in the array is located by index and the index value starts with zero.

Array Syntex

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

Dynamic declaration

Datatype[] arrayname =new DataType[size];

Static declaration

DataType[] arrayname =new DataType[] {20,40};
datatype[] arrayName;

The square brackets [] is the notation used to declare an array where the dataType can be primitive (such as Integers or Strings), sObject (Account or Contact or ay custom object etc.,) or userdefined (variable of class type) types.

Example:

Integer[]       ages;     // 30, 40, 50..
String[]         names;   // 'ranjith', 'krishnan'
Account[]      accs;
Position__c[] pos;  // position__c is a custom object for an example

The above statements will define the array with null values. The memory has to be allocated using the keyword “new” as below.

The size of array can be set using the below syntax.

Integer[] ages = new Integer[4];  // 4 denotes the size of your array
String[]  names;
names = new String[10];           // 10 elements can be stored in this array

Account[] accs = new Account[2];
account    a1 = new account();
a1.name = 'sfdcmeet';
a1.phone = '45454';

account a2 = new account();
a2.name = 'training';
a2.phone = '1234';

accs[0] = a1;
accs[1] = a2;

//Adding elements
Integer[] ages = new Integer[5];
ages[0] = 30;
ages[1] = 40;
ages[2] = 25;
ages[3] = 50;
ages[4] = 32;

Hence, in memory the elements are placed in the below format and each element can be located by index.
——————————–
0 | 1 | 2 | 3 | 4 |
——————————–
30 | 40 | 25 | 50 | 32 |
———————————
To display the entire array values in your log.
System.debug(ages);

Display each element using “for loop”:

for(Integer i = 0; i < 5; i++){
   system.debug('i = ' + ages[i]);
}

Array can be initialized while declaring itself as below

Integer[] RollNos = new Integer[]{1001, 3003, 2002, 4004};
for(Integer i = 0; i < 4; i++){
   system.debug('RollNos = ' + RollNos[i]);
}

Array of sObject

Account a1;
a1 = new Account();
a1.name = 'Test Account1';
a1.Industry = 'Education';

//The above statements can be replaced with single statement as below.
Account a1 = new Account(Name='Test Account1', Industry='Education');
Account a2 = new Account(Name='Test Account2', Industry='Apparel');
Account[] accArray = new Account[]{a1, a2 };

system.debug(accArray);

forEach loop in apex to iterate collections.
syntax:
for(dataType variable: array){

}

//Example 1
Integer[] ages = new Integer[]{30,40,20,50,32};

// syntax of for each loop -> for(dataType variable: array){}
for(Integer a: ages){    //value="{!ages}" var="a"
system.debug(a);
}
//size method to get the size of an array
for(Integer i = 0; i < ages.size(); i++){  //size() - to get the size of array
system.debug('i = ' + ages[i]);
}
//Example 2
String[] names = new String[]{'Sam','Vinesh','Ameen'};
for(String s:names){
system.debug(s);
}
//Example 3 - Array of sObject
Account a1 = new Account(Name='CTS', Phone='123');
Account a2 = new Account(Name='TCS', Phone='345');
Account[]  accs = new Account[]{a1, a2};

for(Account a: accs){
system.debug('Name : ' + a.name + '; ' + 'Phone : ' + a.phone);
}

system.debug(accs.size());

To conclude, Arrays retains the order of elements, accessed by index, accepts duplicates.

Note:
Please be noted that Arrays of arrays are not allowed. So arrays in Salesforce can only be an one-dimensional. In Apex, the array is a notation used to declare single dimensional list. List is a type of collection type in apex.

Difference between Array and Collections

ArraysCollections
Array is a collection of similar elements.It is a collections of homogeneous and heterogeneous elements.
Arrays can not grow and shrink dynamically.Collections can grow and shrink dynamically.
Arrays can be accessed faster and consume less memory.Collections are slow when compared with arrays and they consume more memory.

Let us understand the working of an Arrays in Apex by writing a simple program to display Array of strings in PageBlockTable. To create an Apex class in Salesforce, login to Salesforce -> Developer console -> File -> File -> New -> Apex class.

  • Enter the Apex class name to create new Apex Class.

Apex Class code

Public class ArrayExample {
    Public String[] myval{set;get;}
    Public String name{get;set;}
    Public ArrayExample() {
        name = 'Prasanth';
        myval = new String[] {'Malli','Adarsh','kiran'};
    }
}

Visualforce Page

When referring Apex class variables in the Visualforce page, we should use getter and setter method.

<apex:page controller="ArrayExample" >
    <apex:form>
        <apex:pageBlock>
            <apex:pageBlockTable value="{!myval}" var="a">
                <apex:column value="{!a}"/>
            </apex:pageBlockTable>
            <apex:outputLabel>{!name}</apex:outputLabel>
        </apex:pageBlock>
    </apex:form>    
</apex:page>

Output

Post a Comment

0Comments
Post a Comment (0)