Java 无法检查 int 是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4059057/
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-08-14 11:05:50  来源:igfitidea点击:

Can't check if int is null

javadictionarynull

提问by Pieter

I'm trying to use a dictionary. Whenever I want to check if an element is present in the dictionary, I do this:

我正在尝试使用字典。每当我想检查字典中是否存在某个元素时,我都会这样做:

int value = results.get("aKeyThatMayOrMayNotBePresent");

if (value != null)
  // ...

But then the compiler says I can't compare an intto a <nulltype>. What's the correct way to check for nullin this case?

但是随后编译器说我无法将 anint与 a进行比较<nulltype>null在这种情况下,检查的正确方法是什么?

采纳答案by darioo

You're comparing a primitive value (int) to null. Since primitives cannot be null, you should use a corresponding object, such as Integer in this case. So, you should write

您正在将原始值 (int) 与 null 进行比较。由于基元不能为空,因此您应该使用相应的对象,例如本例中的 Integer。所以,你应该写

Integer value = results.get("aKeyThatMayOrMayNotBePresent");

回答by duffymo

int is a primitive type; you can compare a java.lang.Integerto null.

int 是一种原始类型;您可以将 ajava.lang.Integer与 null进行比较。

回答by Peter Alexander

Get the Objectand check if that is null.

获取Object并检查它是否为空。

Object valueObj = results.get("...");
if ( valueObj != null )
{
    Integer value = (Integer)valueObj;
}

回答by josefx

Your null check is too late.

您的空检查为时已晚。

int value = results.get("aKeyThatMayOrMayNotBePresent");

This line already converts the reference to a primitive int. It will throw a NullPointerException if the return value of get is null.

这一行已经将引用转换为一个原语int。如果 get 的返回值为 null,它将抛出 NullPointerException。

The correct way would be to use Integerinstead of int.

正确的方法是使用Integer而不是int.

Integer value = results.get("aKeyThatMayOrMayNotBePresent");

This way value wont be a primitive type and your null check is valid.

这样 value 不会是原始类型,并且您的 null 检查有效。

回答by starblue

You should use Mapinstead of Dictionary, Dictionaryis obsolete.

您应该使用Map代替Dictionary,Dictionary已过时。

With Mapyou can use containsKey()instead, which in my opinion is more readable:

有了Map你可以用containsKey()代替,这在我看来是更具可读性:

if (results.containsKey(key))
{
    int value = results.get(key);
    [...]
}

In my experience this is not slower than your approach, despite the apparent double access to the map. If this is executed often enough for performance to matter then it is optimized away.

以我的经验,这并不比您的方法慢,尽管对地图的明显双重访问。如果这执行的频率足以使性能变得重要,那么它就会被优化掉。