Should List<Object>.add(index, listElement) work if the index is at the upper bound?

It'd be nice if it added it, but I think you hit the nail on the head with:

I'd expect the exception if the index was greater than the current list size or less than zero.

If it was greater than the list size then it'd definitely be out of bounds, but with zero-based counting then it'd be out of bounds if it's equal to the size also.

| 0 | 1 | 2 | <-Size is 3 but 3 would be OOB

I guess both set() and add() assume the index specified already exists. Whether you should be able to add to a list this way comes down to the specification of the class and method, though personally I think you should expect it to function the way it does.

If it automatically allocated space in memory for the case when index is 0, then it should also do that when the index is 100,000 and as such programmer mistakes could lead to vast swathes of wasted memory. It'd probably just be size * sizeof(reference)) and not catastrophic, but I think the reasoning is valid.


listInstance.add(Integer, Object) method is for adding new value at existing position index. e.g;

This won't give exception:

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

i.add(0);
i.add(0,1);

But this:

List <integer> i = new List<integer>();
i.add(0,1); // there is no index `0`

Because at this point list size is 0. So there should not be any index position to filled or replace. As you add an element to the list it size become 1 means it now have position index start from 0. So 0 is open to replace/add or remove.

However after adding element at 0 position its next index position is open to fill because new position has been allocated to shifted item and list size is increased by 1.

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

i.add(0);
i.add(0,1);
i.add(1,1);
i.add(2,1);

We can add element to the next position to the current max index only.

If you want add element to last position:

Integer lastEle = i.size()-1; 
if(lastEle != -1)
{
   i.add(lastEle ,25);
}

Tags:

Apex