为什么我在创建地图时会收到 IllegalArgumentException?
Why am I getting an IllegalArgumentException when creating a Map?
我正在尝试创建城市和温度的地图,但它抛出 IllegalArgumentException
。这是我正在做的事情:
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);
如果我一个一个添加就没问题:
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?
因为您在实例化中有一个重复键:"London"
。 Map
和 Set
的 immutable static factories 不允许重复(如果映射条目的键重复,则该条目是重复的)——在创建时不允许——因此根本不允许。限制由抛出的 IllegalArgumentException
.
表现出来
虽然从技术上讲您没有做任何不兼容的事情,但图书馆的作者认为这是一个(可能是复制粘贴)错误。为什么你添加一个项目只是为了在几行之后覆盖它?
这让我想到...
If I add them one by one there's no problem
这就是您的想法,只是您可能没有意识到您的地图包含的条目将比您输入的条目少 1 个。重复条目会覆盖前一个条目("last one wins" 规则)。当因此而发生错误时,将会有很多问号。出于这个原因,fail-fast 方法有其优点(尽管我不提倡它只是更好)。
提示一下,在创建地图时,如果您稍微格式化一下,会更容易看到其内容:
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
);
所述
They reject duplicate keys at creation time. Duplicate keys passed to
a static factory method result in IllegalArgumentException
.
因为,每个奇数参数是键,偶数参数是Map
的值。您需要确保奇数参数是唯一的。
另一方面,Map.put
将替换相同键的旧值。
我正在尝试创建城市和温度的地图,但它抛出 IllegalArgumentException
。这是我正在做的事情:
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);
如果我一个一个添加就没问题:
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?
因为您在实例化中有一个重复键:"London"
。 Map
和 Set
的 immutable static factories 不允许重复(如果映射条目的键重复,则该条目是重复的)——在创建时不允许——因此根本不允许。限制由抛出的 IllegalArgumentException
.
虽然从技术上讲您没有做任何不兼容的事情,但图书馆的作者认为这是一个(可能是复制粘贴)错误。为什么你添加一个项目只是为了在几行之后覆盖它?
这让我想到...
If I add them one by one there's no problem
这就是您的想法,只是您可能没有意识到您的地图包含的条目将比您输入的条目少 1 个。重复条目会覆盖前一个条目("last one wins" 规则)。当因此而发生错误时,将会有很多问号。出于这个原因,fail-fast 方法有其优点(尽管我不提倡它只是更好)。
提示一下,在创建地图时,如果您稍微格式化一下,会更容易看到其内容:
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
);
They reject duplicate keys at creation time. Duplicate keys passed to a static factory method result in
IllegalArgumentException
.
因为,每个奇数参数是键,偶数参数是Map
的值。您需要确保奇数参数是唯一的。
另一方面,Map.put
将替换相同键的旧值。