java 以某种方式将空值放入 HashMap 是不可能的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10851631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:50:57  来源:igfitidea点击:

Putting null value into HashMap is not possible somehow

javaandroidnullhashmap

提问by Stan

I'm writing an Android application and use HashMap<String,MyClass>. According to Java and Android documentation the HashMap should accept both null keys and values. But, strangely, I can't put null value into my map. In the code:

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

myMap.put(1, null);

I'm getting the error:

我收到错误:

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

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

Why is that? What can be wrong and how to fix?

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

回答by Anthony Atkinson

The value is not the issue in this case. Since the HashMap is declared to have a String key and you're trying to put an int key in, it's not complaining about the value but the key.

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

回答by ditkin

Because you are using a key of type int and it was declared to except a key of type String.

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

回答by Dobry

HashMap is declared to have a String key and you're trying to put an int key.

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

In your case you can use the following:

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

myMap.put("1", null);

or

或者

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

回答by Maruf Hossain

If you want to use Integer as a key of your Map then change your Map definition to:

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

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

Other wise use String as key of your Map:

其他明智的使用 String 作为您的地图的键:

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

回答by iKing

first try to figure out the error then look for the desired solution.Because most of our problem will be solved by looking the error description. It is telling clearly that you have used int instead of string.

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