Итак, у меня есть очень странный баг. Я наткнулся на него, когда изначально использовал keySet() для перебора первых 10 ключей большого TreeMap. Один из ключей возвращал значение null, что, насколько я понимаю, невозможно. Поэтому я написал тестовый код ниже:
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++;
}
И получить следующие результаты:
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...
Я обрезал карту после первой десятки, так как там много чего еще, но все это ключ со значением.
Итак, мой вопрос заключается в следующем: почему я получаю нулевое значение при использовании ключа для прямого получения (ключа) из TreeMap, но EntrySet возвращает правильный ключ и значение?
Вот мой компаратор, так как я заказываю 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;
}
}
}
И TreeMap строится следующим образом:
ValueComparator bvc = new ValueComparator(allMatches);
TreeMap<String, Integer> sortedMap = new TreeMap<String, Integer>(bvc);
//Sort the HashMap
sortedMap.putAll(allMatches);
Где allMatches — это HashMap<String, Integer>
String
по умолчанию... - person Louis Wasserman   schedule 24.02.2012TreeMap.get(entry.getKey())
должно возвращать то же самое, что иentry.getValue()
, при условии, чтоentry
получено из вводаmap
. Это проблема. - person Louis Wasserman   schedule 25.02.2012