0

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.

Mady Daby
  • 1,271
  • 6
  • 18
  • Is `arr` an int array or an Integer array? – khelwood May 15 '21 at 12:16
  • Always include declarations in code. It is more readable. – Lazar Đorđević May 15 '21 at 12:28
  • See `containsKey` for a more expressive solution as in: `if (hmap2.containsKey(arr1[i]))`... . Note that a hashmap can contain an key=>null mapping but you seem to be interested in whether the key exists. –  May 15 '21 at 13:26

3 Answers3

2

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.

Abanoub Asaad
  • 510
  • 4
  • 14
0

You just need to delete the not null check. The primitive int can’t be null and thus it’s always true

SgtOmer
  • 200
  • 1
  • 1
  • 8
0

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

Difference between int and Integer

Rohith V
  • 1,089
  • 1
  • 9
  • 23