Now this next method can be useful but potentially dangerous.
If you need to add an element to a very specific index of the list, you can use an overloaded version of the add method: add(index, element)
. Let's use this method to add 210.00
to the 1st index. This will cause all elements after the 1st index to be shifted 1 place to the right:
List<Decimal> listOfAmounts = new List<Decimal>(); listOfAmounts.add(50.45); listOfAmounts.add(320.85); Decimal firstAmountInList = listOfAmounts[0]; // 50.45 Decimal secondAmountInList = listOfAmounts[1]; // 320.85 listOfAmounts.add(1, 210.00); firstAmountInList = listOfAmounts[0]; // 50.45 - this didn't change secondAmountInList = listOfAmounts[1]; // 210.00 this was injected into the list Decimal thirdAmountInList = listOfAmounts[2]; // 320.85 this was moved up an index
This can be dangerous because we can't insert into an index that does not exist:
List<Decimal> listOfAmounts = new List<Decimal>(); listOfAmounts.add(50.45); listOfAmounts.add(320.85); listOfAmounts.add(2, 210.00); // There is no 2nd index, there is only a 0th and 1st index currently
The last line above will cause a runtime error: System.ListException: List index out of bounds: 2
. Anytime you see this error, you're program has tried to interact with an index that does not exist, in this case, index 2.