Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 446
  • Last Modified:

multiple null as key to hashmap

can we have multiple null  as key to hashmap. i was not clear on this concept. please advise.thanks  in advance
0
gudii9
Asked:
gudii9
  • 5
2 Solutions
 
for_yanCommented:
null can be a key,
but second time as any other key with HashMap it will overwrite thae Entry
0
 
for_yanCommented:
So you cannot have multiple nulls as a key, as well as any other key - it should be unique
0
 
for_yanCommented:
As you see "ab" is overwritten by "cd" :

        HashMap<String,String> m = new HashMap<String,String>();
        m.put(null, "ab");

         m.put(null, "cd");
        
          m.put("a","nm");

        String sss = m.get(null);

        System.out.println(sss);
        

Open in new window


Output:

cd

Open in new window


0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
for_yanCommented:



see here:
http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html

This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.)
0
 
for_yanCommented:

As opposed to HashMap,
Hashtable does not allow null as the key  and throws NullPointer exception

       Hashtable<String,String> t = new Hashtable<String,String>();

         t.put(null, "ef");

Open in new window



Exception in thread "main" java.lang.NullPointerException
	at java.util.Hashtable.put(Hashtable.java:399)

Open in new window

0
 
reijnemansCommented:
Hi

As described by for_jan it's not possible to add multiple null key-values into a hashmap. But why do you want to put multiple null values as key in a hashmap? Maybe we could figure out a solution for that?

Regards,

reijnemans


0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now