java - Treemap get throws NullPointerException -
follwing java class testentry.java
private void initializemaptest() { eventmap = new treemap<string,string>(); //put value 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 @ line } }
as per knowledge eventmap doesnot allow null values, hence keyset of eventmap not have null values, if value of key in eventmap null, while try put in maptest, shoukd not throw null pointer exception, because respective comparator allows null values
but why getting exception
java.lang.nullpointerexception @ java.util.treemap.cmp(treemap.java:1911) @ java.util.treemap.get(treemap.java:1835) @ kidiho.sa.client.reports.reportentry.initializemaptest(testentry.java:22)
it throw nullpointerexception
because in treemap api get() method throwing nullpointerexception
deliberately if null
.
final entry<k,v> getentry(object key) { // offload comparator-based version 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; }
Comments
Post a Comment