75

What does a HashMap<String,String> return when I call map.get("key") and I don't have an entry with the key "key" in the HashMap?

1

3 Answers 3

127

It returns null. It's written in the documentation.

Returns: the value to which the specified key is mapped, or null if this map contains no mapping for the key

The first thing to do when you have such a specific question is to consult the documentation. Java APIs are documented reasonably well and tell you what is returned, what exceptions are thrown and what each argument means.

Sign up to request clarification or add additional context in comments.

Comments

16

You can:

Check in your IDE

Map<String, String> map = new HashMap<String, String>();
map.put("foo", "fooValue");
System.out.println(map.get("bar")); // null

Check documentation - HashMap get() method description:

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

1 Comment

again HashMap<String> is not possible in standard java library, unless you have created your own HashMap, it should be with two type arguments like Map<String, Object> map = new HashMap<String, Object>() or something like that.
0

Careful - If you initialize it using

Map.of(key, val, key, val)

and then do a

get('key-that-isnt-there') 

then you'll get a null pointer exception.

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.