Counting the entries
The length of a dictionary is the number of key-value pairs it holds. For a HashMap, you get it from the size() method:
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Charlie", 72);
int count = scores.size();
System.out.println(count); // 3
size() returns an int. It counts entries, not keys plus values, so three pairs give 3 and not 6. A new, empty map has size 0.
Checking for an empty map
To ask whether a map has any entries, use isEmpty(), which returns a boolean:
System.out.println(scores.isEmpty()); // false
HashMap<String, Integer> empty = new HashMap<>();
System.out.println(empty.size()); // 0
System.out.println(empty.isEmpty()); // true
scores.isEmpty() means the same as scores.size() == 0, and it reads more naturally in an if condition.
How the size changes
The size follows the entries, so it moves in predictable ways:
- Putting a new key raises the size by 1.
- Putting an existing key replaces its value, so the size stays the same.
- Removing a key with
remove(key)lowers it by 1. Removing a key that isn't there changes nothing. clear()removes everything and brings the size back to 0.
HashMap<String, Integer> m = new HashMap<>();
m.put("A", 1);
m.put("B", 2);
m.put("C", 3);
m.put("A", 9); // existing key
System.out.println(m.size()); // 3
m.remove("A");
System.out.println(m.size()); // 2
m.remove("nothing");
System.out.println(m.size()); // 2
m.clear();
System.out.println(m.size()); // 0
A key that maps to null still counts as an entry. After m.put("B", null), the key "B" is still in the map and the size still includes it.
Using the size
The count is handy for calculations that depend on how many entries there are, such as an average. Add up the values, then divide by size():
int sum = 0;
for (int v : scores.values()) {
sum += v;
}
System.out.println(sum / scores.size()); // 84
System.out.println((double) sum / scores.size()); // 84.66666666666667
The first line uses integer division and drops the fractional part. Casting one operand to double keeps it. The calculation has one hazard: with an empty map, the size is 0, and dividing an int by zero throws an ArithmeticException. Check isEmpty() first:
HashMap<String, Integer> none = new HashMap<>();
if (none.isEmpty()) {
System.out.println("no scores yet");
}
Without the guard, a program that reports an average would crash on its very first run, before any score has been added. With double arithmetic there would be no exception at all, but the result would be NaN, which is no more useful.
That guard is the usual reason to ask about emptiness before doing work on a map.
The lesson's exercise
The starting code builds a map with three scores:
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Charlie", 72);
The task has one step: store the number of entries. Declare an int named count below the map and assign it scores.size(). The map has three distinct keys, so count holds 3.
The complete code is:
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Charlie", 72);
int count = scores.size();
The variable count keeps the value it had when you read it. If you add another entry afterwards, count does not update by itself; call scores.size() again to get the new number.
Gotchas
- The name differs between types. A map and the other collections use the method
size(). AStringuseslength(), and an array uses the fieldlengthwith no parentheses. For"abc",int[] {1, 2, 3}and anArrayListof two items, those give 3, 3 and 2. - Don't confuse the size with the last index. A map has no indexes, so there is nothing to subtract from. The size is simply the count.
- Size is not capacity. A
HashMapmanages its internal storage by itself and grows as needed. The number fromsize()is only the number of entries you can see. - Calling
size()is cheap. The map keeps the count up to date, so the call doesn't scan the entries and is fine to use in a loop condition. - A variable that is
nullhas no size. If the map reference itself isnull,size()throws aNullPointerException. An empty map and a missing map are different things.
Key takeaways
map.size()returns the number of key-value pairs as anint.map.isEmpty()istrueexactly when the size is 0.- Adding a new key grows the size, while overwriting an existing key does not.