Apex Array Notation & List Elasticity

Continuing my PD1 study of data types from yesterday, today’s topic surrounded collections.

I was aware of the ability to use array notation for lists, but I didn’t realize that using brackets to add values to a list ignores that list’s elasticity.

… lists are elastic and can grow as needed provided that you use the List add method to add new elements.

From https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_lists.htm

So, this will work:

String[] colors = new String[1];
colors[0] = 'red';
colors.add('blue');

This will not:

String[] colors = new String[1];
colors[0] = 'red';
colors[1] = 'blue';

ERROR: System.ListException: List index out of bounds: 1

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.