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. Summary - add(e) appends to the end and grows the list. - add(i, e) inserts at index i, shifting later elements right. - get(i) returns the element at index i. - size() returns the current element count. These four operations are the backbone of nearly every ArrayList program you will write.

Challenge: Nth Element