vote

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.

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’

Some common methods of list:

add(element) It adds an element into the list. it always adds at the last. List<String> l = new List<String>();
l.add(‘abc’);
System.debug(l); // (‘abc’)
size() Returns the number of elements in the list. l.add(‘def’);
System.debug(l.size()); // 2
System.debug(l); // (‘abc’,’def’)
get(index) Returns the element on the ith index. System.debug(l.get(0)); // ‘abc’
remove(index) Removes the element on ith index. l.remove(1);
System.debug(l); // (‘abc’)
clone() Makes a duplicate of a list. List<String> l2 = l.clone();
set() Sets the element on the ith position of the list. If there is already a value then 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 datatypes only. l.sort();
System.debug(l);//(’aaa’,‘abc’,’def’)
isEmpty() Returns true if the list is empty. System.debug(l.isEmpty()); // false
clear() Clears the list. l.clear()

Our Recent Blog

Share This Post
×