Here is JDK documentation about null object or array
Thrown when an application attempts to use
null
in a case where an object is required. These include: - Calling the instance method of a
null
object. - Accessing or modifying the field of a
null
object. - Taking the length of
null
as if it were an array. - Accessing or modifying the slots of
null
as if it were an array. - Throwing
null
as if it were aThrowable
value.
Exception in thread "main" java.lang.NullPointerException
at java.util.Arrays.mergeSort(Arrays.java:1144)
at java.util.Arrays.sort(Arrays.java:1079)
at java.util.Collections.sort(Collections.java:117)
The reason is List, Set, HashMap etc allows null value which is ok to build the list/map/set, but will throw exception if we do sort using Collections.sort() method.
Here is one example about HashMap.
HashMap<String, String> testMap = new HashMap<String, String>();
testMap.put(null, "apple");
testMap.put("key2", "orange");
testMap.put("key3", "pear");
List<String> keylist = new ArrayList<String>(testMap.keySet());
List<String> valuelist = new ArrayList<String>(testMap.values());
System.out.println(keylist);
System.out.println(valuelist);
Collections.sort(keylist); // this will throw NPE
Collections.sort(valuelist); // this will not throw NPE
However, for Hashtable, putting null to the map will throw NPE, for instance
Hashtable<String, String> testTable = new Hashtable<String, String>();
testTable.put(null, "1"); //this will throw NPE
testTable.put(null, "2");
testTable.put("key3", "3");
Exception in thread "main" java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:399)
Here is the difference between Hashtable and HashMap
HashMap | Hashtable | |
Thread-safe | N | Y |
Key nullable | Y | N |
Better performance | Y | N |
No comments:
Post a Comment