Null Keys or values in HashMap/Hashtable 4

Can java.util.HashMap store null key/value pair?
Yes it can, However only one null key is allowed, but can store many null values against non-null keys
 
Example

public class HashMapTest
{
public static void main(String args[])
{
HashMap h = new HashMap();
h.put(null,null);
h.put(null, "1");
h.put("1", null);
h.put("1", "1");
h.put("2", null);
System.out.println(h.get(null).toString());
System.out.println(h.get("1"));
System.out.println(h.get("2"));
}
}

output
1
1
null
 
Can java.util.Hashtable store null key/value pair?
No it can’t. We cannot store null keys or null values or both in the Hashtable, java.lang.NullPointerException will be thrown.
 
import java.util.Hashtable;
 

public class HashTableTest
{
public static void main(String args[])
{
Hashtable h = new Hashtable();
//h.put(null,null); //NullPointerException
//h.put(null, "1"); //NullPointerException
//h.put("1", null); //NullPointerException
h.put("1", "1");
//h.put("2", null); //NullPointerException
//System.out.println(h.get(null).toString()); //NullPointerException
System.out.println(h.get("1")); //1
System.out.println(h.get("2")); //null
}
}

Null Keys or values in HashMap/Hashtable
Rate this post

4 thoughts on “Null Keys or values in HashMap/Hashtable

  1. Reply www.seoteam.sg Jul 4,2014 9:57 pm

    Greetings I am so thrilled I found your web site, I really found you by error, while I was researching
    on Yahoo for something else, Nonetheless I am here
    now and would just like to say many thanks for a incredible post and
    a all round thrilling blog (I also love the theme/design), I don’t have time to go through it all at the moment but I have bookmarked it and also added in your RSS feeds, so when I have time I will be back
    to read a great deal more, Please do keep up the fantastic
    job.

  2. Reply row cotton jersey Mar 20,2015 5:16 pm

    We’re a group of volunteers and starting a new scheme
    in our community. Your web site provided us with valuable info to
    work on. You have done a formidable job and our whole
    community will be grateful to you.

  3. Reply google analytics api May 16,2015 5:08 am

    Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your webpage?
    My blog is in the very same area of interest as yours and my users would certainly benefit from
    a lot of the information you provide here.
    Please let me know if this ok with you. Thanks!

Leave a Reply