Treemap get throws NullPointerException

Follwing is my java class TestEntry.java

private void initializemapTest() { eventMap = new TreeMap<String,String>(); //Put some value into eventMap mapTest = new TreeMap<String, String>( new Comparator<String>() { public int compare( String key1, String key2 ) { if( key1 == null ) { if( key2 == null ) { return 0; } else { return 1; } } else { if( key2 == null ) { return -1; } else { return key1.compareTo( key2 ); } } } } ); for( String s : eventMap.keySet() ) { mapTest.put( eventMap.get( s ), s ); //Error at this line } } 

According to my knowledge, eventMap does not allow null values, so the eventMap keyset has no null values, if the value of any key in eventMap is null, while I try to put it in mapTest, it shoukd does not throw a null pointer exception, therefore that its corresponding comparator is nullable

But why am I getting this exception

  java.lang.NullPointerException at java.util.TreeMap.cmp(TreeMap.java:1911) at java.util.TreeMap.get(TreeMap.java:1835) at kidiho.sa.client.reports.ReportEntry.initializemapTest(TestEntry.java:22) 
+4
source share
3 answers

It will throw a NullPointerException because in the TreeMap method the api get () intentionally throws a NullPointerException if it is null .

 final Entry<K,V> getEntry(Object key) { // Offload comparator-based version for sake of performance if (comparator != null) return getEntryUsingComparator(key); if (key == null) throw new NullPointerException(); Comparable<? super K> k = (Comparable<? super K>) key; Entry<K,V> p = root; while (p != null) { int cmp = k.compareTo(p.key); if (cmp < 0) p = p.left; else if (cmp > 0) p = p.right; else return p; } return null; } 
+6
source

From TreeMap:

  final Entry<K,V> getEntry(Object key) { // Offload comparator-based version for sake of performance if (comparator != null) return getEntryUsingComparator(key); if (key == null) throw new NullPointerException(); Comparable<? super K> k = (Comparable<? super K>) key; Entry<K,V> p = root; while (p != null) { int cmp = k.compareTo(p.key); if (cmp < 0) p = p.left; else if (cmp > 0) p = p.right; else return p; } return null; } 

That is: TreeMap does not allow null keys, so you cannot do:

 tm.put(null, something) 

And afterwards you cannot do

 tm.get(null) 

According to the behavior of the TreeMap, these operations are virtually meaningless.

+1
source

Like others, you cannot use the null value as the TreeMap key; it throws a NullPointerException .

You are not getting a NullPointerException from the same place, probably because your first card has a registered comparator and the second not.

+1
source

All Articles