为什么我在创建Map时会收到IllegalArgumentException?
我正在尝试创建城市和温度的地图,但它正在抛出 IllegalArgumentException
。这就是我正在做的事情:
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?
因为实例化中有一个重复的密钥:London
。 不可变的静态工厂 地图
和设置
不允许重复(如果地图条目的密钥重复,则地图条目重复) - 不在创建时间 - 因此一点也不。限制表现为抛出 IllegalArgumentException
。
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?
这让我想到...
如果我逐个添加它们没有问题
If I add them one by one there's no problem
这就是你的想法,只有你可能没有意识到你的地图将包含少于你输入的1个条目。重复条目会覆盖前一个条目(最后一个胜利规则)。当因此发生错误时,会出现很多问号。出于这个原因,故障快速方法有其优点(虽然我不会提倡它只是更好)。
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
);