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

Here is a very simple test that fails with a

System.ListException: List index out of bounds: 0

Sample code:

List<integer> intList = new List<integer>();
intList.add(0, 2);

This seems very odd to me, shouldn’t it just put the integer 2 into the currently empty list? The exception occurs whenever the index parameter equals the current list size. I’d expect the exception if the index was greater than the current list size or less than zero.

Now when I want to insert something at the start of the list I need to first check if the list is empty. E.g.

public void someMethod(List<integer> existingList) {
    // Existing code ...
    integer intToPrepend = 1;

    // Insert at start of the list
    if(existingList.isEmpty()) {
        existingList.add(intToPrepend);
    } else {
        existingList.add(0, intToPrepend);
    }
}

Should it be possible to use add(Integer, Object) to append an element to the end of a list?


Part of my confusion probably comes from my .NET background and the following C# not throwing an ArgumentOutOfRangeException.

List<int> intList = new List<int>();
intList.Insert(0, 2);

Answer

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.

Attribution
Source : Link , Question Author : Daniel Ballinger , Answer Author : Matt Lacey

Leave a Comment