Chapter 3 - Apex Datatypes and Operators >

List Array Notation in APEX

List Array Notation in APEX

← Hide

What You’ll Learn

What is List Array Notation?

Methods of List Collection

What Is List Array Notation?

Developers comfortable with Array notation can also use it while using Lists. Array and List syntax can be used interchangeably. Array notation is a notation where a list’s elements are referenced by enclosing the index number in square brackets after the list’s name.

Syntax Of List Array Notation

``````String[] nameList = new String[4];
//or
String[] nameList2 = new List<String>();
//or
List<String> nameList3 = new String[4];
// Set values for 0, 1, 2 indices
nameList[0] = 'Bhavna';
nameList[1] = 'Bhavya';
nameList[2] = 'Swati';
// Size of the list, which is always an integer value
Integer listSize = nameList.size();
// Accessing the 2nd element in the list, denoted by index 1 System.debug(nameList[1]); // ‘Bhavna’
``````

Methods Of List Collection

Some common methods of List collection:

 Methods Definition Example add(element) It adds an element to the list. It always adds up at the end. List l = new List(); l.add(‘abc’); System.debug(l); //(‘abc’) size() Returns the number of elements in the list. l.add(‘def’); System.debug(l.size()); // 2 get(index) Returns the element on the ith   index. System.debug(l.get(0)); // (‘abc’) remove(index) Removes the element on the ith index. l.remove(0); System.debug(l); // (‘abc’) clone() Make a duplicate of a list. List l2 = l.clone(); set() Sets the element on the ith position of the list. If there is already a value then the value gets overridden. l.add(‘def’);  l.add(‘ghi’); System.debug(l); // (‘abc’,‘def’,‘ghi’) l.set(2,’aaa’);  System.debug(l); // (‘abc,‘def’,‘aaa’) sort() Sorts the item in ascending order but works with primitive data types only. Returns true if the list is empty. l.sort();  System.debug(l); // ( ’aaa’,‘abc’,’def’ ) isEmpty() Sorts the item in ascending order but works with primitive data types only. Returns true if the list is empty. System.debug(l.isEmpty()); // false clear() Clears the list. l.clear();