Adding and Accessing: add, get, size

Part of: ArrayList

Building a List. You start with an empty ArrayList and add elements to it. The one-argument add appends to the end: Each call increases size() by one. After three adds, list.size() returns 3. Reading Elements with get. To read an element, call get(index) . Indices run from 0 to size() - 1: Accessing get(3) here throws an IndexOutOfBoundsException because valid indices are only 0, 1, 2. Always keep your index strictly less than size(). Inserting at a Position. The two-argument form add(index, element) inserts at a given position and shifts everything from that index onward one slot to the right: This is more expensive than appending because elements must shift, but it is essential when order matters. A Classic Loop. Use an indexed loop to visit every element: Notice the condition is i < list.size(), never i <= list.size(). Going one past the end is a frequent off-by-one bug. What usually goes wrong. What you see What caused it How to fix it --- --- --- IndexOutOfBoundsException on the last pass of a loop The condition used i <= list.size() Use i < list.size(). The last valid index is size() - 1 An element got pushed aside instead of replaced add(i, e) inserts and shifts everything a

Challenge: Nth Element