gpt4 book ai didi

java - 将错误类型的对象放入 Map 中

转载 作者:行者123 更新时间:2023-11-30 03:10:07 25 4
gpt4 key购买 nike

考虑这段代码,其中我有两个 map ,一个 Map<String, Integer>和一个 Map<String, String> 。我将第二个分配给一个对象,并将该对象转换为一个映射,以便我可以将所有该映射放入第一个映射中。

    Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
Map<String, String> otherMap = new HashMap<>();
otherMap.put("two", "two");

Object obj = otherMap;

map.putAll((Map<String,Integer>)obj);

Assert.assertFalse(map.get("two") instanceof Integer);
Assert.assertEquals("{one=1, two=two}", map.toString());

第一个断言确保我的 Map 的第二个元素不是 Integer,那么为什么 putAll 没有失败?第二个断言只是为了表明这张 map 没有明显的问题。本地图首次分配给对象时,如何确保 putAll 方法失败?

谢谢

最佳答案

泛型是一个编译时功能,并且不会在运行时强制执行。您的代码将在编译时带有未经检查的警告,准确地告诉您这一点:您的代码可能会出现意外行为。

为了大大简化,所有 Map s 被视为 Map<Object, Object>在运行时。 (不是真的,但有点。)

关于java - 将错误类型的对象放入 Map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33765010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com