+ Start a Discussion
DSLDSL 

can't add to list element zero List.add(0)

This is not documented so at a minimum, perhaps the docs should be updated.

 

I tried to add an element to a zero-sized list and put it in the first position, and apex threw an exception. Why should I not be allowed to do this?

 

List<Integer> i = new List<Integer>();

i.add(0,44);

 

Anand@SAASAnand@SAAS
why would you not do i.add(44) instead?
bob_buzzardbob_buzzard

This does make sense if you come from a Java programming background, Apex being somewhat related to Java. 

 

This is because you have created a zero sized list, and when you specify an index to the list.add method, you are overwriting the existing element at that position (which may be null).  With a zero sized list, there is no element to overwrite, hence the error.  

 

List.add is effectively a shortcut that extends the list and inserts the value in the final position.

 

The Java documentation notes that an exception will be thrown if an index is specified to list.add, and the index is greater than the size of the list.  Unfortunately the Apex documentation doesn't often cover exceptions that can be thrown by methods. 

prageethprageeth

Hello DSL;

Since your List is zero sized, it has no slot to insert your integer(44) . If at least your List size is  '1' you can use the "add(0, 44);" method. 

If you need to insert a data in to the zero th position, first check whether the list is empty. You can do it as below.

if (i.size() > 0) {

i.add(0,44);

} else {

i.add(44);