java - 树状图放置似乎正在删除条目

标签 java long-integer comparator treemap consistent-hashing

我正在尝试使用带有无符号长比较器的树形图。然而,树状图的放置似乎正在删除整个。没有比较器,它工作得很好,但我似乎无法弄清楚比较器出了什么问题。示例代码如下:

公共(public)类主要{

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

最佳答案

else 分支应返回 1,而不是 -1:

@Override
public int compare(Long o1, Long o2) {
    if (isLessThanUnsigned(o1, o2)) {
        return -1;
    } else if (o1.equals(o2)) {
        return 0;
    } else {
        return 1; // <<== HERE: 1, not -1
    }
}

关于java - 树状图放置似乎正在删除条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16409932/

相关文章:

java - 如何使用docx4j设置下载的word文档的名称?

c++ - 将 64 位整数转换为 7 位字符数组

c - 长比较

c++ - std::map,自定义比较器的设计约束

java - AssertJ 记录断言结果

java - 链表在位置添加

java - 如何访问二维数组的第二部分

r - R中对长数的操作

Java Arrays.Sort(arr, 比较器);不接受争论

Java 对 List<Value> 的 HashMap 值进行排序