Java – the key in treemap returns null
So I have a very strange mistake When I first used keyset () to iterate over the first 10 keys of a large treemap, I stumbled upon it One of the keys is to return null, which is impossible as far as I understand So I wrote the test code below:
int i = 0; for (Map.Entry<String,Integer> es : sortedMap.entrySet()){ if (i >= 10) { break; } if (sortedMap.containsKey(es.getKey())){ System.out.println(es.getKey() + ":" + sortedMap.get(es.getKey())); } else { System.out.println("Key " + es.getKey() + " does not exist,yet..."); System.out.println("This does work: " + es.getKey() + ":" + es.getValue()); System.out.println("This does NOT work: " + es.getKey() + ":" + sortedMap.get(es.getKey())); } i++; }
The following results were obtained:
SOAP:967 'excerpt'::679 'type'::679 Key 'author_url': does not exist,yet... This does work: 'author_url'::679 This does NOT work: 'author_url'::null 'date'::679 Android:437 TLS:295 message:283 server:230 monthly:215 <<<<<<<<<<<<<<<<<<<<DUMPING MAP! {SOAP=967,'excerpt':=679,'type':=679,'author_url':=679,'date':=679,Android=437,TLS=295,message=283,server=230,monthly=215...
I cut off the map after the top ten because there are more maps, but all these are a valuable key
So my question is: why do I get null when I use the key to get the key directly from treemap, but the entryset returns the correct key and value?
This is my comparator because I ordered it on integer:
class ValueComparator implements Comparator<Object> { Map<String,Integer> base; public ValueComparator(Map<String,Integer> base) { this.base = base; } public int compare(Object a,Object b) { if ((Integer) base.get(a) < (Integer) base.get(b)) { return 1; } else if ((Integer) base.get(a) == (Integer) base.get(b)) { return 0; } else { return -1; } } }
The construction of treemap is as follows:
ValueComparator bvc = new ValueComparator(allMatches); TreeMap<String,Integer> sortedMap = new TreeMap<String,Integer>(bvc); //Sort the HashMap sortedMap.putAll(allMatches);
Allmatches is HashMap < string, integer >
Solution
As can be seen from the iteration order displayed in treemap, you are using a custom comparator [otherwise, iterations will be arranged in dictionary order]
Note that according to JavaDocs:
If your comparator does not apply these rules – the behavior is undefined and may display strange results – as you can see
Edit: [in response to an edit question] your quarantine uses identity [operator =] to check two integers Note that integer is an object – so operator = = returns true only if it is the same object You should use equals () to check that two integers are the same – or even better – using integer compareTo()