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);