function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
gsarguccigsargucci 

List 'size()' bug? String 'split()' bug? Or my misunderstanding?

When I try to execute this code snippet:

 

String strVal = '';
List <String> lstVals = strVal.split(',');
System.debug ('***** List: ' + lstVals + ', size: ' + lstVals.size ());
for (String s : lstVals)
  System.debug ('***** List element [' + s + ']');

 

 

String strVal = '';

List <String> lstVals = strVal.split(',');

System.debug ('***** List: ' + lstVals + ', size: ' + lstVals.size ());

for (String s : lstVals)

  System.debug ('***** List element [' + s + ']');

 

I get the following output (some lines omitted for clarity:

 

15:24:15.186|USER_DEBUG|[3,1]|DEBUG|***** List: (), size: 1

15:24:15.186|USER_DEBUG|[5,3]|DEBUG|***** List element []

So, it seems that somehow I'm getting back an empty list of size '1'.  I would expect back a list of size 0, since there are no tokens in my string being split (it's an empty string).
Am I missing something, or is this a peculiar bug?  If so, is it a bug in 'split' or 'size'?
Thanks!

 

Best Answer chosen by Admin (Salesforce Developers) 
rungerrunger

no, lst[0] will be '', not null.

All Answers

rungerrunger

The semantics of split() are such that the list you get back always has at least one element.  You are splitting the empty string, and so you're getting back an array of size 1, where the element in the array is the empty string.

 

This is modeled after the semantics in Java's similar String.split() method.

gsarguccigsargucci

Thanks Rich.  What is the right way to test for this case?  'if (lst.size () == 1 && lst[0] == null)' ?

 

Thanks!

rungerrunger

no, lst[0] will be '', not null.

This was selected as the best answer
gsarguccigsargucci

Thanks!