【问题标题】:Putting null value into HashMap is not possible somehow无法以某种方式将空值放入 HashMap
【发布时间】:2012-06-06 18:35:26
【问题描述】:

我正在编写一个 Android 应用程序并使用 HashMap<String,MyClass>。根据 Java 和 Android 文档,HashMap 应该接受空键和空值。但是,奇怪的是,我不能将 null 值放入我的地图中。在代码中:

myMap.put(1, null);

我收到了错误:

The method put(String, MyClass) in the type HashMap<String,MyClass> is not applicable for the arguments (int, null).

这是为什么呢?有什么问题以及如何解决?

【问题讨论】:

  • 你只需要先看一下语言的基础,然后来这里。

标签: java android null hashmap


【解决方案1】:

在这种情况下,值不是问题。由于 HashMap 被声明为具有 String 键并且您尝试将 int 键放入其中,因此它不是在抱怨值而是在抱怨键。

【讨论】:

  • 你真是个天才!我会在 9 分钟内接受你的回答 ;-) 该网站现在不允许这样做。
【解决方案2】:

因为您使用的是 int 类型的键,并且它被声明为除了 String 类型的键。

【讨论】:

    【解决方案3】:

    HashMap 被声明为具有 String 键,而您正在尝试放置一个 int 键。

    在您的情况下,您可以使用以下内容:

    myMap.put("1", null);
    

    myMap.put(1 + "", null);
    

    【讨论】:

      【解决方案4】:

      首先尝试找出错误然后寻找所需的解决方案。因为我们的大部分问题都将通过查看错误描述来解决。它清楚地表明您使用的是 int 而不是 string。

      【讨论】:

        【解决方案5】:

        如果您想使用 Integer 作为 Map 的键,请将您的 Map 定义更改为:

        Map<Integer,MyClass> myMap = new HashMap();
        myMap.put(1, null);
        

        其他明智的做法是使用 String 作为 Map 的键:

        Map<String,MyClass> myMap = new HashMap();
        myMap.put("1", null);
        

        【讨论】:

          猜你喜欢
          • 2016-02-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多