I'm trying to create a map of cities and temperature, but it's throwing an IllegalArgumentException
. Here's what I'm doing:
Map<String, Integer> tempMap = Map.of("London", 13, "Paris", 17, "Amsterdam", 13,
"Madrid", 21, "Rome", 19, "London", 13, "Bonn", 14,
"Moscow", 7, "Barcelona", 20, "Berlin", 15);
If I add them one by one there's no problem:
Map<String, Integer> tempMap = new Hashmap<>(); // or LinkedHashMap
tempMap.put("London", 13);
tempMap.put("Madrid", 21);
tempMap.put("Moscow", 7);
// etc.
Why does this happen? Aren't the contents supposed to be the same?
Why does this happen?
Because you have a duplicate key in your instantiation: "London"
. The immutable static factories for Map
and Set
do not allow duplicates (a map entry is duplicate if its key is duplicate) - not during creation time - therefore not at all. The restriction is manifested by a thrown IllegalArgumentException
.
Although technically you're not doing anything incompatible, the writers of the library assumed that it's a (probably copy-paste) mistake. Why would you add an item just to override it a few lines later?
Which brings me to...
If I add them one by one there's no problem
That's what you think, only you might not have realized that your map will contain 1 entry less than you put in it. The duplicate entry overrides the previous one ("last one wins" rule). When a bug will happen because of this there are going to be a lot of question marks thrown around. For this reason, the fail-fast method has its advantages (though I won't advocate it's just plain better).
As a tip, when creating the map it's easier to see its content if you format it a bit:
Map<String, Integer> tempMap = Map.of(
"London", 13,
"Paris", 17,
"Amsterdam", 13,
"Madrid", 21,
"Rome", 19,
"London", 13, // !
"Bonn", 14,
"Moscow", 7,
"Barcelona", 20,
"Berlin", 15
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With