java · level 2 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Lists can change: swap, squeeze in and items.
.set(1, "pear") swaps the item at index 1 for a new one. .add(0, "kiwi") squeezes an item in at index 0, and every item after it will along one place to make room.
.remove takes an item out. Give it an index, like .remove(0), or the item itself, like .remove("plum"). The items after the gap shift back, so their indexes all drop by one.
Ask for an index the list does not have, and Java stops with an IndexOutOfBoundsException. A list of 3 items has indexes 0, 1 and 2, the same as an array.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> fruit = new ArrayList<>();
fruit.add("apple");
fruit.add("banana");
fruit.add("plum");
fruit.set(1, "pear");
fruit.add(0, "kiwi");
fruit.remove("plum");
System.out.println(fruit);
}
} .set replaces an item, but .add with an index makes the list one longer.
guess first
Someone leaves the queue. Who is first now?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> queue = new ArrayList<>();
queue.add("Ada");
queue.add("Ben");
queue.add("Cara");
queue.remove(0);
System.out.println(queue.get(0) + " " + queue.size());
}
}
your turn
Your turn. Fix up the playlist.
On line 8, swap the song at index 1 for one you like. On line 9, squeeze a new song in at the start. Then press run.
output
press run to see what happens
fix it
The last stop will not show. Can you fix it?
output
press run to see what happens
- Java stopped with an
IndexOutOfBoundsExceptionon line 8. Which index does it ask for? - There are 3 stops, so
stops.size()is 3. The indexes are 0, 1 and 2. - Change
stops.get(stops.size())tostops.get(stops.size() - 1)on line 8, then press run.
nailed it
you can change a list any way you like. :D
.set(i, value)swaps the item at index i..add(i, value)squeezes in, and.removetakes out.- Items shift along, so indexes change after a removal.
new words in your collection
- remove
- shift
This lesson isn’t saved. A free account remembers every lesson you finish.