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. What usually goes wrong. What you see What caused it How to fix it --- --- --- The wrong number disappeared from an Integer list remove(2) matched remove(int index), deleting position 2 rather than the value 2 Write remove(Integer.va
Challenge: Replace then Remove