java · level 2 · unit 1 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An is a list that grows when you add to it.
An array has a fixed , so you must know how many slots you need before you start. An ArrayList is a list that grows: start it empty, then add as many items as you like. Borrow it with import java.util.ArrayList; at the top.
ArrayList<String> pets = new ArrayList<>(); makes an empty list of strings. The , < and >, say what type of item it keeps. The empty pair after new tells Java to copy the type from the left.
.add("cat") puts an item on the end. .size() gives its size, the number of items right now. .get(0) hands back the item at index 0. Printing a whole list shows every item, like [cat, dog].
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> pets = new ArrayList<>();
pets.add("cat");
pets.add("dog");
pets.add("hamster");
System.out.println(pets);
System.out.println(pets.size());
System.out.println(pets.get(0));
}
} Use .size() for lists, .length() for strings and .length for arrays.
guess first
The queue keeps growing. What will this show?
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("Amir");
queue.add("Bella");
System.out.println(queue.size());
queue.add("Chen");
System.out.println(queue.size() + " " + queue.get(2));
}
}
your turn
Your turn. Pack your bag.
Add three things to pack, one on each of lines 5 to 7. Then press run to see your bag and how many items it holds.
output
press run to see what happens
fix it
The guest count will not work. Can you fix it?
output
press run to see what happens
- Java says
cannot find symbolon line 7. Arrays have.length, but isguestsan array? - A list counts its items with a method that has brackets, not with
.length. - Change
guests.lengthtoguests.size()on line 7, then press run.
nailed it
your list grows as you go. :D
- An
ArrayListgrows as you add items. .addputs a new item on the end..size()counts the items, and.get(i)reads one.
new words in your collection
- ArrayList
- angle brackets
- size
This lesson isn’t saved. A free account remembers every lesson you finish.