Anand Pandey
Anand Pandey

Reputation: 11

Difference between HashMaps put and add

What is the difference between

ans.put(key, new ArrayList());

and

ans.get(key).add(s);

ans is the HashMap and s is a String object.

Upvotes: 0

Views: 10532

Answers (2)

szeak
szeak

Reputation: 335

ans.put(key, new ArrayList());

This command insert a new key with a new empty ArrayList as value to the HashMap, if the key does not exists in the map, or exchange the existing key's value to the new empty ArrayList.

ans.get(key).add(s);

This command asks the HashMap for the key's value, and adds a new String value to the stored ArrayList. This command throws a NullPointerException, if key does not exists in the HashMap.

HashMap's put method stores a key-value pair. HashMap's get method asks for a value of a key-value pair by the key.

Upvotes: 2

maio290
maio290

Reputation: 6732

get is getting an element from the hashmap by key, you are calling the add function on the element FROM the hashmap.

put is adding a new element to the hashmap.

But for the future, just read the docs.

Upvotes: 3

Related Questions