1

if a HashMap is empty and I check for .containsKey() I get a null answer.

My Problem is that If I want to check for null I get an error message

if(containsKey == null || !containsKey){

I receive the error message

Operator '==' cannot be applied to 'boolean', 'null'

Can someone tell me why this is happening. I thought that this should work

1
  • 2
    containsKey seems to be of type boolean, so how can that ever be null? Why do you think it can be? Commented Jan 11, 2017 at 21:49

4 Answers 4

6

Check that the map isn't null (not that HashMap.containsKey(T) returned null, because it didn't - it can't. It returns a boolean primitive, which can only be true or false).

if (map != null && map.containsKey(someKey)) {
    // ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the HashMap .isEmpty() method to check if your hashmap is empty or not.

1 Comment

Yeah but I cant check if it is empty if it doesnt exist
0

containsKey can't be null as it is the method being called. Try checking if the map itself is null.

1 Comment

No worries. I was hoping to lead you to the answer as I find that helps people learn but guy above gave you the answer so that's good I guess.
0

Booleans are primitives, and primitives will never be null.
Only Object classes can be null.

Following this argument, you can do this for object class Integer:

Integer myObject = 1;

if (myObject != null){
    ...
}

But you cannot do this for int, which is a primitive like booleans:

int myPrimitve = 1;

if (myPrimitve == null){
    ...
}

Your IDE will show the error Operator == cannot be applied to int, null

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.