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
}
}
As per my knowledge eventMap doesnot allow null values, hence keyset of eventMap does not have any null values, if value of any key in eventMap is null, while i try to put it in mapTest, it shoukd not throw any null pointer exception, because its respective comparator allows null values
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)
It will throw NullPointerException
because in TreeMap api get() method is throwing NullPointerException
deliberately if that 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;
}
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 doesn't allow null keys, so you cannot do:
tm.put(null, something)
And subsequently, you cannot do
tm.get(null)
As according to the TreeMap behaviour, those operations actually don't make sense
As other said, you can't use a null
value as a TreeMap key, it will throw a NullPointerException
.
You're not getting the NullPointerException
from the same place probably because your first map has a registered comparator and the second has none.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With