Why am I getting an IllegalArgumentException when creating a Map?

て烟熏妆下的殇ゞ 提交于 2019-12-08 17:51:55

问题


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?


回答1:


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
);



回答2:


As stated in Map.of()

They reject duplicate keys at creation time. Duplicate keys passed to a static factory method result in IllegalArgumentException.

Since, each odd-number parameters are keys and even-number are values of for the Map. You need to make sure that odd-number parameter are unique.

On the other hand, Map.put will replace the old value for same key.



来源:https://stackoverflow.com/questions/46620234/why-am-i-getting-an-illegalargumentexception-when-creating-a-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!