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> called fruits.

  • Add "apple" and "banana", then print fruits.

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" from fruits, then print fruits.

  • 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> called ages, 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 prices contains the key "milk", print its price. Otherwise, print No milk.

  • Loop over prices.keySet() and print each item like apple: 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> called cart and add "apple", "bread" and "apple".

  • Loop over cart, add prices.get(item) to a total, then print "Total: " + total.

  • Print "Items: " + cart.size().

More in Java Objects

Previous: Classes and Objects · Next: Inheritance