Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4189821

HashMap.toString throws exception if HashMap contains null key or value.

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P3 P3
    • 1.2.2
    • 1.2.0
    • core-libs
    • None


      When a HashMap contains null keys or values,
      converting any entries (as returned by the entrySet
      method) to strings throws a NullPointerException

      import java.util.Map;
      import java.util.Set;
      import java.util.HashMap;

      public class HashMapTest {
          public static void main(String[] arg) {
              Map map = new HashMap();
              map.put("hello", "world");
              System.out.println(map);
              System.out.println(map.entrySet());
              
              try {
                  map = new HashMap();
                  map.put(null, "world");
                  System.out.println(map);
                  System.out.println(map.entrySet());
              }
              catch (NullPointerException e) {
                  e.printStackTrace();
              }

              try {
                  map = new HashMap();
                  map.put("hello", null);
                  System.out.println(map);
                  System.out.println(map.entrySet());
              }
              catch (NullPointerException e) {
                  e.printStackTrace();
              }
          }
      }

      Output generated is:

      {hello=world}
      [hello=world]
      {null=world}
      java.lang.NullPointerException:
              at java.util.HashMap$Entry.toString(HashMap.java:630)
              at java.lang.String.valueOf(String.java:1540)
              at java.util.AbstractCollection.toString(Compiled Code)
              at java.lang.String.valueOf(String.java:1540)
              at java.io.PrintStream.print(PrintStream.java:423)
              at java.io.PrintStream.println(PrintStream.java:542)
              at HashMapTest.main(HashMapTest.java:35)
      {hello=null}
      java.lang.NullPointerException:
              at java.util.HashMap$Entry.toString(HashMap.java:630)
              at java.lang.String.valueOf(String.java:1540)
              at java.util.AbstractCollection.toString(Compiled Code)
              at java.lang.String.valueOf(String.java:1540)
              at java.io.PrintStream.print(PrintStream.java:423)
              at java.io.PrintStream.println(PrintStream.java:542)
              at HashMapTest.main(HashMapTest.java:45)

            jjb Josh Bloch (Inactive)
            jjb Josh Bloch (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: