ArrayList and HashMap
Programming Languages · Java Objects · 15 min
Use lists that grow and maps that look things up by name.
A list that grows: ArrayList
Arrays have a fixed size. An ArrayList can grow and shrink. The type of item goes in angle brackets, and .add() puts an item on the end. The import at the top brings it in.
ArrayList<String> todo = new ArrayList<>();
todo.add("shop");
System.out.println(todo); // [shop]
Create an
ArrayList<String>calledfruits.Add
"apple"and"banana", then printfruits.
get and size
.get(i) reads the item at index i (starting at 0, like arrays). .size() tells you how many items the list has right now.
todo.get(0); // first item
todo.size(); // how many
Print the first fruit with
get.Print how many fruits there are with
size.
Removing items
.remove() takes an item out. Everything after it slides down to fill the gap, and the size shrinks by one.
todo.remove("shop");
Remove
"banana"fromfruits, then printfruits.Print the new size.
Look things up: HashMap
A HashMap stores pairs: a key and its value, like a word and its meaning in a dictionary. .put(key, value) saves a pair; .get(key) finds the value.
For whole-number values write Integer, the object version of int.
HashMap<String, Integer> stock = new HashMap<>();
stock.put("pens", 12);
stock.get("pens"); // 12
Create a
HashMap<String, Integer>calledages, and put"Ada"with 36 and"Alan"with 41.Print Alan's age with
get.
Checking and looping
.containsKey(key) answers true or false: is this key in the map? .keySet() gives you all the keys, so a for-each loop can visit every pair. (A HashMap doesn't promise any order.)
for (String item : stock.keySet()) {
System.out.println(item + ": " + stock.get(item));
}
If
pricescontains the key"milk", print its price. Otherwise, printNo milk.Loop over
prices.keySet()and print each item likeapple: 3.
Put it together: a shopping cart
The shop's prices are in a HashMap. Put some items in a cart (an ArrayList), then loop over the cart to add up the bill.
Create an
ArrayList<String>calledcartand add"apple","bread"and"apple".Loop over
cart, addprices.get(item)to atotal, then print"Total: " + total.Print
"Items: " + cart.size().
More in Java Objects
Previous: Classes and Objects · Next: Inheritance