Skip to main content

Maps

The Aims​

This lab will introduce you to the Java HashMap.

Declaring and initialising variables​

  1. Within the main method you created in the previous lab, create a new map with an Integer key and a value of Account. The key will represent the account number.

  2. Add 5 accounts to the map, with keys of 1,2,3,4 and 5.

  3. Print out the size of the map.

  4. Add a new account to the map with a key of 3.

  5. Print out the size of the map and the value of the item with a key of 3, to check that the map contains only the updated version of account number 3.

Click here to view the sample solution

public static void main(String[] args) {

Map<Integer, Account> accountsMap = new HashMap<>();
accountsMap.put(1, new Account(3000.0, "Frank"));
accountsMap.put(2, new Account(1200.0, "Grace"));
accountsMap.put(3, new Account(1800.0, "Heidi"));
accountsMap.put(4, new Account(2200.0, "Ivan"));
accountsMap.put(5, new Account(900.0, "Judy"));

System.out.println("The map contains " + accountsMap.size() + " accounts." );

accountsMap.put(3, new Account(15.0, "Hannah"));

System.out.println("The map contains " + accountsMap.size() + " accounts." );
System.out.println(accountsMap.get(3));
}