List Methods

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.

The following are the instance parameters for List.

Note
In the table below, List_elem represents a single element of the same type as the list.
Name Arguments Return Type Description
add Any type e Void Adds an element e to the end of the list. For example:
List<Integer> myList = new List<Integer>();
myList.add(47);
Integer myNumber = myList.get(0);
system.assertEquals(myNumber, 47);
add Integer i

Any type e

Void Inserts an element e into the list at index position i. 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 l Void Adds all of the elements in list l to the list that calls the method. Note that both lists must be of the same type.
addAll Set s Void Add all of the elements in set s to the list that calls the method. Note that the set and the list must be of the same type.
clear Void Removes all elements from a list, consequently setting the list's length to zero
clone List (of same type) Makes a duplicate copy of a 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:

Invoice_Statement__c a = new 
   Invoice_Statement__c(
    Description__c='Invoice1');

Invoice_Statement__c b = new 
     Invoice_Statement__c();

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

Invoice_Statement__c[] q2 = 
   q1.clone();
q1[0].Description__c = 
   'New description';

System.assertEquals(
      q1[0].Description__c,
      'New description');
System.assertEquals(
      q2[0].Description__c, 
      'New description');

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

deepClone Boolean opt_preserve_id

Boolean opt_preserve_readonly_timestamps

Boolean opt_preserve_autonumber

List (of same object type) Makes a duplicate copy of a list of sObject records, including the sObject records themselves. For example:
Invoice_Statement__c a = new 
   Invoice_Statement__c(
      Description__c='Invoice1');

Invoice_Statement__c b = 
    new Invoice_Statement__c();

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

Invoice_Statement__c[] q2 = 
   q1.deepClone();
q1[0].Description__c = 'New description';

System.assertEquals(
     q1[0].Description__c, 
     'New description');

System.assertEquals(
     q2[0].Description__c,
     'Invoice1'); 
Note
deepClone only works with lists of sObjects, not with lists of primitives.

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.

Note
For Apex saved using SalesforceAPI version 22.0 or earlier, the default value for the opt_preserve_id argument is true, that is, the IDs are preserved.

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.

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.

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<Invoice_Statement__c> invs = 
    [SELECT CreatedById, 
    CreatedDate, LastModifiedById, 
    LastModifiedDate, Description__c 
    FROM Invoice_Statement__c 
    WHERE Id = :a.Id OR Id = :b.Id];

// Clone list while preserving  
    
// timestamp and user ID fields. 
    
Invoice_Statement__c[] q3 = 
   invs.deepClone(false,true,false);

// Verify timestamp fields are  
    
// preserved for the first  
    
// list element.  
    
System.assertEquals(
    q3[0].CreatedById, 
    invs[0].CreatedById);
System.assertEquals(
    q3[0].CreatedDate, 
    invs[0].CreatedDate);
System.assertEquals(
    q3[0].LastModifiedById,
    invs[0].LastModifiedById);
System.assertEquals(
    q3[0].LastModifiedDate,
    invs[0].LastModifiedDate);

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

get Integer i Array_elem Returns the list element stored at index i. For example,
List<Integer> myList = new List<Integer>();
myList.add(47);
Integer myNumber = myList.get(0);
system.assertEquals(myNumber, 47);

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. For example:

List<String> colors = new String[3];
colors[0] = 'Red';
colors[1] = 'Blue';
colors[2] = 'Green';
getSObjectType Schema.SObjectType Returns the token of the sObject type that makes up a list of sObjects. Use this with describe information to determine if a list contains sObjects of a particular type. For example:
Invoice_Statement__c a = 
   new Invoice_Statement__c();
insert a;
// Create a generic sObject  
    
// variable s 
    
SObject s = Database.query
  ('SELECT Id FROM ' +
   'Invoice_Statement__c ' + 
   'LIMIT 1');

// Verify if that sObject  
    
// variable is  
    
// an invoice statement token 
    
System.assertEquals(
s.getSObjectType(), 
Invoice_Statement__c.sObjectType);

// Create a list of generic sObjects  
    
List<sObject> q = 
   new Invoice_Statement__c[]{};

// Verify if the list of sObjects  
    
// contains invoice statement tokens 
    
System.assertEquals(
q.getSObjectType(), 
Invoice_Statement__c.sObjectType);

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

For more information, see Understanding Apex Describe Information.

isEmpty Boolean Returns true if the list has zero elements
iterator Iterator Returns an instance of an iterator. From the iterator, you can use the iterable methods hasNext and next to iterate through the list. For example:
global class CustomIterable 
   implements 
   Iterator<Invoice_Statement__c>{

   List<Invoice_Statement__c> 
      invoices {get; set;} 
   Integer i {get; set;} 

 public CustomIterable(){ 
  invoices = 
  [SELECT Id, Description__c +
  FROM Invoice_Statement__c +
  WHERE Description__c = 'false']; 

       i = 0; 
   }   

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

 global Invoice_Statement__c next(){ 
    // 8 is an arbitrary  
    
    // constant in this example. 
    
    // It represents the  
    
    // maximum size of the list. 
    
    if(i == 8){ i++; return null;} 
    i=i+1; 
    return invoices[i-1]; 
 } 
}
Note
You do not have to implement the iterable interface to use the iterable methods with a list.
remove Integer i Array_elem Removes the element that was stored at the ith index of a list, returning the element that was removed. For 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 i

Any type e

Void Assigns e to the position at list index i. For example:
List<Integer> myList = new Integer[6];
myList.set(0, 47);
myList.set(1, 52);
system.assertEquals(myList.get(1), 52);

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. For example:

List<String> colors = new String[3];
colors[0] = 'Red';
colors[1] = 'Blue';
colors[2] = 'Green';
size Integer Returns the number of elements in the list. For 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 Void Sorts the items in the list in ascending order. You can only use this method with lists composed of primitive data types. 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:
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);

For more information on lists, see Lists.

© Copyright 2000–2011 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.