1
我正在嘗試使用無符號長比較器的樹形圖。然而,樹形圖的看起來似乎是刪除entires。沒有比較器,它工作得很好,但我似乎無法弄清楚比較器有什麼問題。下面的實施例的代碼:樹圖似乎是刪除條目
公共類主要{
public static void main(String args[]) {
class UnsignComparator implements Comparator<Long> {
@Override
public int compare(Long o1, Long o2) {
if (isLessThanUnsigned(o1, o2)) {
return -1;
} else if (o1.equals(o2)) {
return 0;
} else {
return -1;
}
}
}
TreeMap<Long, String> consistent = new TreeMap<Long, String>(
new UnsignComparator());
System.out.println("Treemap with comparator");
consistent.put(1L, "a");
System.out.println("1L: " + consistent.containsKey(1L));
consistent.put(2L, "b");
System.out.println("1L: " + consistent.containsKey(1L));
System.out.println("2L: " + consistent.containsKey(2L));
consistent.put(3L, "c");
System.out.println("1L: " + consistent.containsKey(1L));
System.out.println("2L: " + consistent.containsKey(2L));
System.out.println("3L: " + consistent.containsKey(3L));
System.out.println("Treemap with comparator keyset");
for (long keys : consistent.keySet()) {
System.out.println(keys);
}
System.out.println("Treemap without comparator");
TreeMap<Long, String> treemap = new TreeMap<Long, String>();
treemap.put(1L, "a");
System.out.println("1L: " + treemap.containsKey(1L));
treemap.put(2L, "b");
System.out.println("1L: " + treemap.containsKey(1L));
System.out.println("2L: " + treemap.containsKey(2L));
treemap.put(3L, "c");
System.out.println("1L: " + treemap.containsKey(1L));
System.out.println("2L: " + treemap.containsKey(2L));
System.out.println("3L: " + treemap.containsKey(3L));
}
//from http://www.javamex.com/java_equivalents/unsigned_arithmetic.shtml
private static boolean isLessThanUnsigned(long n1, long n2) {
return (n1 < n2)^((n1 < 0) != (n2 < 0));
}
}
結果如下:
Treemap with comparator
1L: true
1L: true
2L: true
1L: false //expected true
2L: true
3L: true
Treemap with comparator keyset
3
2
1
Treemap without comparator
1L: true
1L: true
2L: true
1L: true
2L: true
3L: true
是的,那是錯的。那真是令人尷尬。 – user2356518 2013-05-07 01:50:17
@ user2356518不要擔心,它會發生很多 - 第二雙眼睛通常有助於發現簡單的錯誤。歡迎來到這個網站! – dasblinkenlight 2013-05-07 01:59:03