List Class

Contains methods for the List collection type.

Namespace

System

Usage

The list methods are all instance methods, that is, they operate on a particular instance of a list. For example, the following removes all elements from myList:

myList.clear();

Even though the clear method does not include any parameters, the list that calls it is its implicit parameter.

For more information on lists, see Lists.

List Constructors

The following are constructors for List.

List<T>()

Creates a new instance of the List class. A list can hold elements of any data type T.

Signature

public List<T>()

Example

// Create a list
List<Integer> ls1 = new List<Integer>();
// Add two integers to the list
ls1.add(1);
ls1.add(2);

List<T>(List<T>)

Creates a new instance of the List class by copying the elements from the specified list. T is the data type of the elements in both lists and can be any data type.

Signature

public List<T>(List<T> listToCopy)

Parameters

listToCopy
Type: List<T>
The list containing the elements to initialize this list from. T is the data type of the list elements.

Example

List<Integer> ls1 = new List<Integer>();
ls1.add(1);
ls1.add(2);
// Create a list based on an existing one
List<Integer> ls2 = new List<Integer>(ls1);
// ls2 elements are copied from ls1
System.debug(ls2);// DEBUG|(1, 2)

List<T>(Set<T>)

Creates a new instance of the List class by copying the elements from the specified set. T is the data type of the elements in the set and list and can be any data type.

Signature

public List<T>(Set<T> setToCopy)

Parameters

setToCopy
Type: Set<T>
The set containing the elements to initialize this list with. T is the data type of the set elements.

Example

Set<Integer> s1 = new Set<Integer>();
s1.add(1);
s1.add(2);
// Create a list based on a set
List<Integer> ls = new List<Integer>(s1);
// ls elements are copied from s1
System.debug(ls);// DEBUG|(1, 2)

List Methods

The following are methods for List. All are instance methods.

add(Object)

Adds an element to the end of the list.

Signature

public Void add(Object listElement)

Parameters

listElement
Type: Object

Return Value

Type: Void

Example

List<Integer> myList = new List<Integer>();
myList.add(47);
Integer myNumber = myList.get(0);
system.assertEquals(myNumber, 47);

add(Integer, Object)

Inserts an element into the list at the specified index position.

Signature

public Void add(Integer index, Object listElement)

Parameters

index
Type: Integer
listElement
Type: Object

Return Value

Type: Void

Example

In the following example, a list with six elements is created, and integers are added to the first and second index positions.

List<Integer> myList = new Integer[6];
myList.add(0, 47);
myList.add(1, 52);
system.assertEquals(myList.get(1), 52);

addAll(List)

Adds all of the elements in the specified list to the list that calls the method. Both lists must be of the same type.

Signature

public Void addAll(List fromList)

Parameters

fromList
Type: List

Return Value

Type: Void

addAll(Set)

Add all of the elements in specified set to the list that calls the method. The set and the list must be of the same type.

Signature

public Void addAll(Set fromSet)

Parameters

fromSet
Type: Set

Return Value

Type: Void

clear()

Removes all elements from a list, consequently setting the list's length to zero.

Signature

public Void clear()

Return Value

Type: Void

clone()

Makes a duplicate copy of a list.

Signature

public List<Object> clone()

Return Value

Type: List<Object>

Usage

The cloned list is of the same type as the current list.

Note that if this is a list of sObject records, the duplicate list will only be a shallow copy of the list. That is, the duplicate will have references to each object, but the sObject records themselves will not be duplicated. For example:

To also copy the sObject records, you must use the deepClone method.

Example

Account a = new 
     Account(Name='Acme',
             BillingCity='New York');

Account b = new Account();
Account[] q1 = new 
     Account[]{a,b};

Account[] q2 = q1.clone();
q1[0].BillingCity = 'San Francisco';

System.assertEquals(
      q1[0].BillingCity,
      'San Francisco');
System.assertEquals(
      q2[0].BillingCity, 
      'San Francisco');

deepClone(Boolean, Boolean, Boolean)

Makes a duplicate copy of a list of sObject records, including the sObject records themselves.

Signature

public List<Object> deepClone(Boolean opt_preserve_id, Boolean opt_preserve_readonly_timestamps, Boolean opt_preserve_autonumber)

Parameters

opt_preserve_id
Type: Boolean
The optional opt_preserve_id argument determines whether the IDs of the original objects are preserved or cleared in the duplicates. If set to true, the IDs are copied to the cloned objects. The default is false, that is, the IDs are cleared.
opt_preserve_readonly_timestamps
Type: Boolean
The optional opt_preserve_readonly_timestamps argument determines whether the read-only timestamp and user ID fields are preserved or cleared in the duplicates. If set to true, the read-only fields CreatedById, CreatedDate, LastModifiedById, and LastModifiedDate are copied to the cloned objects. The default is false, that is, the values are cleared.
opt_preserve_autonumber
Type: Boolean
The optional opt_preserve_autonumber argument determines whether the autonumber fields of the original objects are preserved or cleared in the duplicates. If set to true, auto number fields are copied to the cloned objects. The default is false, that is, auto number fields are cleared.

Return Value

Type: List<Object>

Usage

The returned list is of the same type as the current list.

Note
  • deepClone only works with lists of sObjects, not with lists of primitives.
  • For Apex saved using Salesforce.comAPI version 22.0 or earlier, the default value for the opt_preserve_id argument is true, that is, the IDs are preserved.

To make a shallow copy of a list without duplicating the sObject records it contains, use the clone method.

Example

This example performs a deep clone for a list with two accounts.

Account a = new 
   Account(Name='Acme', 
           BillingCity='New York');

Account b = new Account(
   Name='Salesforce');

Account[] q1 = new 
     Account[]{a,b};

Account[] q2 = q1.deepClone();
q1[0].BillingCity = 'San Francisco';

System.assertEquals(
     q1[0].BillingCity, 
     'San Francisco');

System.assertEquals(
     q2[0].BillingCity,
     'New York'); 
This example is based on the previous example and shows how to clone a list with preserved read-only timestamp and user ID fields.
insert q1;

List<Account> accts =
   [SELECT CreatedById, 
   CreatedDate, LastModifiedById, 
   LastModifiedDate, BillingCity 
   FROM Account 
   WHERE Name='Acme' OR 
     Name='Salesforce'];

// Clone list while preserving 
// timestamp and user ID fields. Account[] q3 = accts.deepClone(false,true,false); // Verify timestamp fields are
// preserved for the first
// list element. System.assertEquals( q3[0].CreatedById, accts[0].CreatedById); System.assertEquals( q3[0].CreatedDate, accts[0].CreatedDate); System.assertEquals( q3[0].LastModifiedById, accts[0].LastModifiedById); System.assertEquals( q3[0].LastModifiedDate, accts[0].LastModifiedDate);

equals(List)

Compares this list with the specified list and returns true if both lists are equal; otherwise, returns false.

Signature

public Boolean equals(List list2)

Parameters

list2
Type: List
The list to compare this list with.

Return Value

Type: Boolean

Usage

Two lists are equal if their elements are equal and are in the same order. The == operator is used to compare the elements of the lists.

The == operator is equivalent to calling the equals method, so you can call list1.equals(list2); instead of list1 == list2;.

get(Integer)

Returns the list element stored at the specified index.

Signature

public Object get(Integer index)

Parameters

index
Type: Integer

Return Value

Type: Object

Usage

To reference an element of a one-dimensional list of primitives or sObjects, you can also follow the name of the list with the element's index position in square brackets as shown in the example.

Example

List<Integer> myList = new List<Integer>();
myList.add(47);
Integer myNumber = myList.get(0);
system.assertEquals(myNumber, 47);
List<String> colors = new String[3];
colors[0] = 'Red';
colors[1] = 'Blue';
colors[2] = 'Green';

getSObjectType()

Returns the token of the sObject type that makes up a list of sObjects.

Signature

public Schema.SObjectType getSObjectType()

Return Value

Type: Schema.SObjectType

Usage

Use this method with describe information to determine if a list contains sObjects of a particular type.

Note that this method can only be used with lists that are composed of sObjects.

For more information, see Understanding Apex Describe Information.

Example

Account a = new Account(name='test');
insert a;
// Create a generic sObject 
// variable s SObject s = Database.query ('SELECT Id FROM Account ' + 'LIMIT 1'); // Verify if that sObject
// variable is
// an Account token System.assertEquals( s.getSObjectType(), Account.sObjectType); // Create a list of
// generic sObjects List<sObject> q = new Account[]{}; // Verify if the list of
// sObjects
// contains Account tokens System.assertEquals( q.getSObjectType(), Account.sObjectType);

hashCode()

Returns the hashcode corresponding to this list and its contents.

Signature

public Integer hashCode()

Return Value

Type: Integer

isEmpty()

Returns true if the list has zero elements.

Signature

public Boolean isEmpty()

Return Value

Type: Boolean

iterator()

Returns an instance of an iterator for this list.

Signature

public Iterator iterator()

Return Value

Type: Iterator

Usage

From the returned iterator, you can use the iterable methods hasNext and next to iterate through the list.

Note
You do not have to implement the iterable interface to use the iterable methods with a list.

See Custom Iterators.

Example

global class CustomIterable 
   implements Iterator<Account>{ 

   List<Account> accs {get; set;} 
   Integer i {get; set;} 

   public CustomIterable(){ 
       accs = 
       [SELECT Id, Name, 
       NumberOfEmployees 
       FROM Account 
       WHERE Name = 'false']; 
       i = 0; 
   }   

   global boolean hasNext(){ 
       if(i >= accs.size()) {
           return false; 
       } else {
           return true; 
       }
   }    

   global Account next(){ 
       // 8 is an arbitrary 
       // constant in this example
       // that represents the
       // maximum size of the list.
       if(i == 8){return null;} i++; return accs[i-1]; } }

remove(Integer)

Removes the list element stored at the specified index, returning the element that was removed.

Signature

public Object remove(Integer index)

Parameters

index
Type: Integer

Return Value

Type: Object

Example

List<String> colors = new String[3];
colors[0] = 'Red';
colors[1] = 'Blue';
colors[2] = 'Green';
String S1 = colors.remove(2);
system.assertEquals(S1, 'Green');

set(Integer, Object)

Sets the specified value for the element at the given index.

Signature

public Void set(Integer index, Object listElement)

Parameters

index
Type: Integer
The index of the list element to set.
listElement
Type: Object
The value of the list element to set.

Return Value

Type: Void

Usage

To set an element of a one-dimensional list of primitives or sObjects, you can also follow the name of the list with the element's index position in square brackets.

Example

List<Integer> myList = new Integer[6];
myList.set(0, 47);
myList.set(1, 52);
system.assertEquals(myList.get(1), 52);
List<String> colors = new String[3];
colors[0] = 'Red';
colors[1] = 'Blue';
colors[2] = 'Green';

size()

Returns the number of elements in the list.

Signature

public Integer size()

Return Value

Type: Integer

Example

List<Integer> myList = new List<Integer>();
Integer size = myList.size();
system.assertEquals(size, 0);

List<Integer> myList2 = new Integer[6];
Integer size2 = myList2.size();
system.assertEquals(size2, 6);

sort()

Sorts the items in the list in ascending order.

Signature

public Void sort()

Return Value

Type: Void

Usage

In the following example, the list has three elements. When the list is sorted, the first element is null because it has no value assigned while the second element has the value of 5:

Note
Using this method, you can sort primitive types, SelectOption elements, and sObjects (standard objects and custom objects). For more information on the sort order used for sObjects, see Sorting Lists of sObjects. You can also sort custom types (your Apex classes) if they implement the Comparable Interface interface.

Example

List<Integer> q1 = new Integer[3];

// Assign values to the first 
// two elements q1[0] = 10; q1[1] = 5; q1.sort(); // First element is null, second is 5 system.assertEquals(q1.get(1), 5);
© Copyright 2000–2014 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.