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. So when this happens I don't want to print the arr[i]
value. How can I do it because it is throwing error can't compare 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.
int can't be null
, but Integer can.
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. Only objects can have a null value. The class Integer represents an int value, but it can hold a null value.
This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.
You just need to delete the not null check. The primitive int can't be null and thus it's always true
The problem can be solved if you use Integer
instead of int
Change your code to Integer value = hmap2.get(arr[i]);
and now value can hold null value.
Refer the difference between Integer and int
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.