So, I have a very strange error. I came across it when I initially used keySet () to repeat the first 10 keys of a large TreeMap. One of the keys returned null, which should not be possible, as I understand it. 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++; }
And get the following results:
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 turned off the card after the first ten, as there are much more, but all this is a key with a value.
So my question is this: why do I get zero when using the key to directly obtain (the key) from the TreeMap, but the EntrySet returns the correct key and value?
Here is my comparator as I order 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; } } }
And TreeMap is built as follows:
ValueComparator bvc = new ValueComparator(allMatches); TreeMap<String, Integer> sortedMap = new TreeMap<String, Integer>(bvc);
Where allMatches is a HashMap<String, Integer>