Reputation: 11
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
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