|
| 1 | +# About Maps |
| 2 | + |
| 3 | +A **Map** is a data structure for storing key value pairs. |
| 4 | +It is similar to dictionaries in other programming languages. |
| 5 | +The [Map][map-javadoc] interface defines the operations you can make with a map. |
| 6 | + |
| 7 | +## HashMap |
| 8 | + |
| 9 | +Java has a number of different Map implementations. |
| 10 | +[HashMap][hashmap-javadoc] is a commonly used one. |
| 11 | + |
| 12 | +```java |
| 13 | +// Make an instance |
| 14 | +Map<String, Integer> fruitPrices = new HashMap<>(); |
| 15 | +``` |
| 16 | + |
| 17 | +~~~~exercism/note |
| 18 | +When defining a `Map` variable, it is recommended to define the variable as a `Map` type rather than the specific type, as in the above example. |
| 19 | +This practice makes it easy to change the `Map` implementation later. |
| 20 | +~~~~ |
| 21 | + |
| 22 | +`HashMap` also has a copy constructor. |
| 23 | + |
| 24 | +```java |
| 25 | +// Make a copy of a map |
| 26 | +Map<String, Integer> copy = new HashMap<>(fruitPrices); |
| 27 | +``` |
| 28 | + |
| 29 | +Add entries to the map using [put][map-put-javadoc]. |
| 30 | + |
| 31 | +```java |
| 32 | +fruitPrices.put("apple", 100); |
| 33 | +fruitPrices.put("pear", 80); |
| 34 | +// => { "apple" => 100, "pear" => 80 } |
| 35 | +``` |
| 36 | + |
| 37 | +Only one value can be associated with each key. |
| 38 | +Calling `put` with the same key will update the key's value. |
| 39 | + |
| 40 | +```java |
| 41 | +fruitPrices.put("pear", 40); |
| 42 | +// => { "apple" => 100, "pear" => 40 } |
| 43 | +``` |
| 44 | + |
| 45 | +Use [get][map-get-javadoc] to get the value for a key. |
| 46 | + |
| 47 | +```java |
| 48 | +fruitPrices.get("apple"); // => 100 |
| 49 | +``` |
| 50 | + |
| 51 | +Use [containsKey][map-containskey-javadoc] to see if the map contains a particular key. |
| 52 | + |
| 53 | +```java |
| 54 | +fruitPrices.containsKey("apple"); // => true |
| 55 | +fruitPrices.containsKey("orange"); // => false |
| 56 | +``` |
| 57 | + |
| 58 | +Remove entries with [remove][map-remove-javadoc]. |
| 59 | + |
| 60 | +```java |
| 61 | +fruitPrices.put("plum", 90); // Add plum to map |
| 62 | +fruitPrices.remove("plum"); // Removes plum from map |
| 63 | +``` |
| 64 | + |
| 65 | +The [size][map-size-javadoc] method returns the number of entries. |
| 66 | + |
| 67 | +```java |
| 68 | +fruitPrices.size(); // Returns 2 |
| 69 | +``` |
| 70 | + |
| 71 | +You can use the [keys] or [values] methods to obtain the keys or the values in a Map as a Set or collection respectively. |
| 72 | + |
| 73 | +```java |
| 74 | +fruitPrices.keys(); // Returns "apple" and "pear" in a set |
| 75 | +fruitPrices.values(); // Returns 100 and 80, in a Collection |
| 76 | +``` |
| 77 | + |
| 78 | +## HashMap uses `hashCode` and `equals` |
| 79 | + |
| 80 | +HashMaps uses the object's [hashCode][object-hashcode-javadoc] and [equals][object-equals-javadoc] method to work out where to store and how to retrieve the values for a key. |
| 81 | +For this reason, it is important that their return values do not change between storing and getting them, otherwise the HashMap may not be able to find the value. |
| 82 | + |
| 83 | +For example, lets say we have the following class that will be used as the key to a map: |
| 84 | + |
| 85 | +```java |
| 86 | +public class Stock { |
| 87 | + private String name; |
| 88 | + |
| 89 | + public void setName(String name) { |
| 90 | + this.name = name; |
| 91 | + } |
| 92 | + |
| 93 | + @Override |
| 94 | + public int hashCode() { |
| 95 | + return Objects.hash(name); |
| 96 | + } |
| 97 | + |
| 98 | + @Override |
| 99 | + public boolean equals(Object obj) { |
| 100 | + if (obj == this) { |
| 101 | + return true; |
| 102 | + } |
| 103 | + if (Objects.equals(Stock.class, obj.getClass()) && obj instanceof Stock other) { |
| 104 | + return Objects.equals(name, other.name); |
| 105 | + } |
| 106 | + return false; |
| 107 | + } |
| 108 | +} |
| 109 | +``` |
| 110 | + |
| 111 | +The `hashCode` and `equals` depend on the `name` field, which can be changed via `setName`. |
| 112 | +Altering the `hashCode` can produce surprising results: |
| 113 | + |
| 114 | +```java |
| 115 | +Stock stock = new Stock(); |
| 116 | +stock.setName("Beanies"); |
| 117 | + |
| 118 | +Map<Stock, Integer> stockCount = new HashMap<>(); |
| 119 | +stockCount.put(stock, 80); |
| 120 | + |
| 121 | +stockCount.get(stock); // Returns 80 |
| 122 | + |
| 123 | +Stock other = new Stock(); |
| 124 | +other.setName("Beanies"); |
| 125 | + |
| 126 | +stockCount.get(other); // Returns 80 because "other" and "stock" are equal |
| 127 | + |
| 128 | +stock.setName("Choccies"); |
| 129 | +stockCount.get(stock); // Returns null because hashCode value has changed |
| 130 | + |
| 131 | +stockCount.get(other); // Also returns null because "other" and "stock" are not equal |
| 132 | + |
| 133 | +stock.setName("Beanies"); |
| 134 | +stockCount.get(stock); // HashCode restored, so returns 80 again |
| 135 | + |
| 136 | +stockCount.get(other); // Also returns 80 again because "other" and "stock" are back to equal |
| 137 | +``` |
| 138 | + |
| 139 | +## Map.of and Map.copyOf |
| 140 | + |
| 141 | +Another common way to create maps is to use [Map.of][map-of-javadoc] or [Map.ofEntries][map-ofentries-javadoc]. |
| 142 | + |
| 143 | +```java |
| 144 | +// Using Map.of |
| 145 | +Map<String, Integer> temperatures = Map.of("Mon", 30, "Tue", 28, "Wed", 32); |
| 146 | + |
| 147 | +// or using Map.ofEntries |
| 148 | +Map<String, Integer> temperatures2 = Map.ofEntries(Map.entry("Mon", 30, "Tue", 28, "Wed", 32)); |
| 149 | +``` |
| 150 | + |
| 151 | +Unlike `HashMap`, they populate the map upfront and become read-only once created. |
| 152 | +[Map.copyOf][map-copyof-javadoc] makes a read-only copy of a map. |
| 153 | + |
| 154 | +```java |
| 155 | +Map<String, Integer> readOnlyFruitPrices = Map.copyOf(fruitPrices); |
| 156 | +``` |
| 157 | + |
| 158 | +Calling methods like `put`, `remove` or `clear` results in an `UnsupportedOperationException`. |
| 159 | + |
| 160 | +[map-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html |
| 161 | +[hashmap-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/HashMap.html |
| 162 | +[map-put-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#put(K,V) |
| 163 | +[map-get-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#get(java.lang.Object) |
| 164 | +[map-containskey-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#containsKey(java.lang.Object) |
| 165 | +[map-remove-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#remove(java.lang.Object) |
| 166 | +[map-size-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#size() |
| 167 | +[map-of-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#of() |
| 168 | +[map-ofentries-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#ofEntries(java.util.Map.Entry...) |
| 169 | +[map-copyof-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#copyOf(java.util.Map) |
| 170 | +[object-hashcode-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Object.html#hashCode() |
| 171 | +[object-equals-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object) |
0 commit comments