You need to sign in to do that
Don't have an account?

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!
no, lst[0] will be '', not null.
All Answers
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.
Thanks Rich. What is the right way to test for this case? 'if (lst.size () == 1 && lst[0] == null)' ?
Thanks!
no, lst[0] will be '', not null.
Thanks!