10

I'm trying to manipulate a List in a for loop and the List isn't getting updated. Pretty much everything in Apex is "pass by reference", so I'd expect it to work. Is there some way to get my list values to get updated?

Here's simple code to replicate

String block = 'blah\tBLAH';
List<String> columnNames;
columnNames = block.split('\t');
    for (String column : columnNames) {
        column = column.toLowerCase().capitalize();
        System.debug(column); //returns 'Blah' for both list entries
    }
System.debug(columnNames); // returns '(blah,BLAH)'

2 Answers 2

16

Your code is updating the local variable but not the reference in the list with the new reference.

One way of updating the list:

for (Integer i = 0; i < columnNames.size(); i++) {
    columnNames[i] = columnNames[i].toLowerCase().capitalize();
}

Note that it is that strings are immutable (cannot be modified once created) that requires the reference in the list to be changed because toLowerCase and capitalize each create a new string. If you had a mutable object in the list the reference in the list could be left untouched.

1
  • haha, I just came to the same conclusion. Oct 6, 2015 at 16:51
8

Apex is actually "pass by value" for primitive types (Integer, String, etc) and "pass by reference for non-primitives (sObjects, for example).

To update a List of Strings, you need to change the syntax:

String block = 'blah\tBLAH';
List<String> columnNames;
columnNames = block.split('\t');
for (Integer i=0; i<columnNames.size(); i++ ) {
    columnNames[i] = columnNames[i].toLowerCase().capitalize();
    System.debug(columnNames[i]);
}
System.debug(columnNames);
1
  • 5
    Apex is pass by reference for strings. But strings are immutable so methods that manipulate them always return new references.
    – Keith C
    Oct 6, 2015 at 16:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .