Reputation: 363
I have a doubt regarding HashMap, as we all know HashMap allows one null key and value pair, My question here is
If I wrote like this,
m.put(null,null);
m.put(null,a);
Will it throw a (error or exception) or will it override the value or what will be the value of returing??
Upvotes: 19
Views: 117034
Reputation: 1
m.put(null,null); // here key=null, value=null
m.put(null,a); // here also key=null, and value=a
Duplicate keys are not allowed in hashmap.
However,value can be duplicated.
Upvotes: 0
Reputation: 397
HashMap don't allow duplicate keys,but since it's not thread safe,it might occur duplicate keys. eg:
while (true) {
final HashMap<Object, Object> map = new HashMap<Object, Object>(2);
map.put("runTimeType", 1);
map.put("title", 2);
map.put("params", 3);
final AtomicInteger invokeCounter = new AtomicInteger();
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
@Override
public void run() {
map.put("formType", invokeCounter.incrementAndGet());
}
}).start();
}
while (invokeCounter.intValue() != 100) {
Thread.sleep(10);
}
if (map.size() > 4) {
// this means you insert two or more formType key to the map
System.out.println( JSONObject.fromObject(map));
}
}
Upvotes: 3
Reputation: 6887
Code example:
HashMap<Integer,String> h = new HashMap<Integer,String> ();
h.put(null,null);
h.put(null, "a");
System.out.println(h);
Output:
{null=a}
It overrides the value at key null.
Upvotes: 9
Reputation: 61885
Each key in a HashMap must be unique.
When "adding a duplicate key" the old value (for the same key, as keys must be unique) is simply replaced; see HashMap.put:
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
Returns the previous value associated with key, or null if there was no mapping for key.
As far as nulls: a single null key is allowed (as keys must be unique) but the HashMap can have any number of null values, and a null key need not have a null value. Per the documentation:
[.. HashMap] permits null values and [a] null key.
However, the documentation says nothing about null/null needing to be a specific key/value pair or null/"a" being invalid.
Upvotes: 13
Reputation: 361
Hashmap type Overwrite that key if hashmap key is same key
map.put("1","1111");
map.put("1","2222");
output
key:value
1:2222
Upvotes: 36
Reputation: 121998
Doesn't allow duplicates in the sense, It allow to add you but it does'nt care about this key already have a value or not. So at present for one key there will be only one value
It silently overrides the value
for null
key. No exception.
When you try to get, the last inserted value with null
will be return.
That is not only with null
and for any key.
Have a quick example
Map m = new HashMap<String, String>();
m.put("1", "a");
m.put("1", "b"); //no exception
System.out.println(m.get("1")); //b
Upvotes: 12