Frage

I am attempting to use a treemap with an unsigned long comparator. However, the treemap's put seems to be deleting entires. Without the comparator, it works just fine but I can't seem to figure out what is wrong with the comparator. Example code below:

public class Main {

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));
}

}

The result is as follows:

    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
War es hilfreich?

Lösung

The else branch should return 1, not -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
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top