← Java from Scratch Lesson 69 of 88 · 10 XP

ArrayList

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

ArrayList is an array that grows by itself:

ArrayList<Integer> nums = new ArrayList<>();
nums.add(5);                 // the int is automatically wrapped into an Integer
int x = nums.get(0);         // and unwrapped back
nums.size()                  // not length!

Under the hood. Inside there's an ordinary Object[] array with spare room (10 places at first). When the room runs out, an array 1.5 times bigger is created and everything is copied — that's why add to the end is O(1) on average. But inserting or removing at the start moves all the elements — O(n). Removing many elements from an ArrayList one by one in a loop is slow, and it's easy to get the indices wrong (after a removal everything has moved).

Removing by index in a loop is safer from the end: for (int i = l.size() - 1; i >= 0; i--).

Task. Read numbers. Remove the repeats (keeping the first occurrence), then remove all the negative ones (with a loop from the end). Print the list and the sum.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.