无法检查 int 是否为 null
我正在尝试使用字典。每当我想检查字典中是否存在某个元素时,我都会这样做:
int value = results.get("aKeyThatMayOrMayNotBePresent");
if (value != null)
// ...
但是编译器说我无法将 int
与
进行比较。在这种情况下检查 null
的正确方法是什么?
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 int
to a <nulltype>
. What's the correct way to check for null
in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您正在将原始值 (int) 与 null 进行比较。由于基元不能为 null,因此您应该使用相应的对象,例如本例中的 Integer。所以,你应该写
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
。如果 get 的返回值为 null,则会抛出 NullPointerException。正确的方法是使用
Integer
而不是int
。这样值就不会是原始类型,并且您的空检查是有效的。
Your null check is too late.
This line already converts the reference to a primitive
int
. It will throw a NullPointerException if the return value of get is null.The correct way would be to use
Integer
instead ofint
.This way value wont be a primitive type and your null check is valid.
int 是原始类型;您可以将
java.lang.Integer
与 null 进行比较。int is a primitive type; you can compare a
java.lang.Integer
to null.您应该使用
Map
而不是字典
,字典
已过时。通过
Map
,您可以使用containsKey()
相反,在我看来更具可读性:根据我的经验,这并不比您的方法慢,尽管明显对地图。如果执行的频率足以使性能变得重要,那么它就会被优化掉。
You should use
Map
instead ofDictionary
,Dictionary
is obsolete.With
Map
you can usecontainsKey()
instead, which in my opinion is more readable: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.
获取
Object
并检查它是否为空。Get the
Object
and check if that is null.