Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting an IllegalArgumentException when creating a Map?

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?

like image 779
user1803551 Avatar asked Oct 07 '17 12:10

user1803551


1 Answers

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
);
like image 199
user1803551 Avatar answered Sep 23 '22 02:09

user1803551