Modifying: set and remove
Part of: ArrayList
Replacing with set The set(index, element) method overwrites the element at a position with a new value and returns the old value . It does not change the size: Use set when an element already exists and you want to change it in place. Contrast this with add(i, e), which inserts and grows the list. Deleting with remove The remove(index) method deletes the element at that index, shifts every later element one slot left, and returns the removed value: After removal, size() decreases by one. The indices of all elements after the removed one change. remove(int) vs remove(Object) This is a famous trap. ArrayList has two remove methods: - remove(int index) removes by position. - remove(Object o) removes the first element equal to o. For an ArrayList<Integer , list.remove(2) removes the element at index 2 , not the value 2. To remove the value, box it: list.remove(Integer.valueOf(2)). On the AP exam this distinction is tested directly. Putting It Together Summary - set(i, e): replaces in place, returns old value, size unchanged. - remove(i): deletes by index, shifts left, size shrinks by one. - Watch the remove(int) vs remove(Object) overload for Integer lists.
Challenge: Replace then Remove