简体   繁体   English

如何将 HashMap 的 function 与 null 值进行比较?

[英]How to compare a get function of HashMap with null value?

I am stuck on a problem, I am not sure how to do it,我被一个问题困住了,我不知道该怎么做,

    for ( int i = 0; i < n1; i++ )
            {
                int value = hmap2.get(arr1[i]);
                if ( value != 0 || value != null )
                {
                    System.out.print(arr1[i]+" ");
                    hmap2.put(arr1[i], --value);
                }
            }

In this code snippet, the variable value will have a null value when arr1[i] doesn't exist in the map.在此代码片段中,当 map 中不存在arr1[i]时,变量value将具有 null 值。 So when this happens I don't want to print the arr[i] value.所以当这种情况发生时,我不想打印arr[i]值。 How can I do it because it is throwing error can't compare arguments?我该怎么做,因为它抛出错误无法比较 arguments? what am I doing wrong?我究竟做错了什么?

I want to make sure that when there is no mapping for arr1[i] in the map, I should skip it and not print it.我想确保当 map 中没有arr1[i]的映射时,我应该跳过它而不打印它。

int can't be null , but Integer can. int不能是null ,但Integer可以。

This will work for you:这将为您工作:

Integer value = hmap2.get(arr1[i]);

In Java, int is a primitive type and it is not considered an object.在 Java 中, int是原始类型,不被视为 object。 Only objects can have a null value.只有对象可以具有 null 值。 The class Integer represents an int value, but it can hold a null value. class Integer表示一个 int 值,但它可以保存一个 null 值。

This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.这种行为不同于一些更纯粹的面向 object 的语言,比如 Ruby,在这些语言中,甚至像 int 这样的“原始”事物也被视为对象。

You just need to delete the not null check.您只需要删除 not null 检查。 The primitive int can't be null and thus it's always true原始 int 不能是 null ,因此它总是正确的

The problem can be solved if you use Integer instead of int如果使用Integer而不是int可以解决问题

Change your code to Integer value = hmap2.get(arr[i]);将您的代码更改为Integer value = hmap2.get(arr[i]); and now value can hold null value.现在值可以保存 null 值。

Refer the difference between Integer and int参考Integer和int的区别

Difference between int and Integer int 和 Integer 的区别

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM