AP® Computer Science A · Unit 4 · Topic 4.8
Insert and Remove: The Shift Nobody Sees
Inserting or removing an element in the middle of a list forces every element after it to shift one spot, so position determines how much work the operation costs.
An array or ArrayList stores elements in order, back to back, by index. There are no gaps allowed. So when you insert at index i, every element currently at i or later has to slide one slot to the right before the new value can go in. Remove works the same way in reverse: everything after the removed spot slides one slot left to close the gap. The cost of either operation depends entirely on how many elements sit after the index you touch.
That is why adding at the front is expensive and adding at the back is cheap. Insert at index 0 of a list holding n elements, and all n elements have to move over. Insert at the end (index n), and nothing moves at all - you are just dropping a value into the next open slot. Removing works the same way: remove(0) shifts every remaining element down by one, while removing the last element shifts nothing.
This connects directly to how ArrayList methods are overloaded. remove(int index) deletes by position, so remove(2) always targets whatever sits at index 2, not the value 2. If you want to delete a specific value instead of a position, you need remove(Object), which searches for a match. Keeping index-based and value-based removal straight matters for every later topic in this unit, especially sorting and searching, where code constantly tracks which index holds what.
Key terms
- shift
- The movement of elements one position left or right to fill or open a gap during remove or insert.
- index
- The numeric position of an element in an array or ArrayList, starting at 0.
- remove(int index)
- An ArrayList method that deletes the element at a given position, not a matching value.
- remove(Object o)
- An ArrayList method that searches for and deletes the first element equal to the given value.
Watch it explained
- How it worksHow does an add at an index push every later element one place to the right?
- Worked exampleTrace inserting X at index 1 in a list of A, B, C, D and find where each element ends up.
- Worked exampleTrace remove(0) on a list of five names and count how many elements have to move.
- Common mistakeWhy doesn't remove(2) on an ArrayList of Integer take out the value 2?
- Going furtherWhat happens to the cost of building a list when every insert goes at the front?
Check yourself
End of topic.