Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap allows duplicates?

Tags:

java

hashmap

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??

like image 599
Nani Avatar asked Dec 12 '13 07:12

Nani


People also ask

Does Java map allow duplicates?

The map implementations provided by the Java JDK don't allow duplicate keys. If we try to insert an entry with a key that exists, the map will simply overwrite the previous entry.

How HashMap store duplicate values?

Let's see how to store our multiple values into an ArrayList, which retains duplicates: MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); map. put("key1", "value1"); map. put("key1", "value2"); map.


3 Answers

Hashmap type Overwrite that key if hashmap key is same key

map.put("1","1111");
map.put("1","2222");

output

key:value
1:2222
like image 174
user3094411 Avatar answered Oct 16 '22 23:10

user3094411


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.

like image 22
user2864740 Avatar answered Oct 16 '22 23:10

user2864740


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
like image 12
Suresh Atta Avatar answered Oct 16 '22 22:10

Suresh Atta