Make TreeMap Comparator tolerate null

2019-05-03 22:58发布

This customized Valuecomparator sorts the TreeMap by it's value. But it doesn't tolerate nullpointexception when searching whether the TreeMap has a certain key. How do i modify the comparator to handle the nullpoint?

    import java.io.IOException;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.TreeMap;



    public class TestTreeMap {

        public static class ValueComparator<T> implements Comparator<Object> {

            Map<T, Double> base;
            public ValueComparator(Map<T, Double> base) {
                this.base = base;
            }

            @Override
            public int compare(Object a, Object b) {
                /*if (((Double) base.get(a) == null) || ((Double) base.get(b) == null)){
                    return -1;
                }   */      
                if ((Double) base.get(a) < (Double) base.get(b)) {
                    return 1;
                } else if ((Double) base.get(a) == (Double) base.get(b)) {
                    return 0;
                } else {
                    return -1;
                }
            }

        }

        public static void main(String[] args) throws IOException { 
            Map<String, Double> tm = new HashMap<String, Double>();
            tm.put("John Doe", new Double(3434.34)); 
            tm.put("Tom Smith", new Double(123.22)); 
            tm.put("Jane Baker", new Double(1378.00)); 
            tm.put("Todd Hall", new Double(99.22)); 
            tm.put("Ralph Smith", new Double(-19.08)); 

            ValueComparator<String> vc = new ValueComparator<String>(tm);
            TreeMap<String, Double> sortedTm = 
                    new TreeMap<String, Double>(vc);
            sortedTm.putAll(tm);

            System.out.println(sortedTm.keySet());
            System.out.println(sortedTm.containsKey("John Doe"));
            // The comparator doesn't tolerate null!!!
            System.out.println(!sortedTm.containsKey("Doe"));
        }


}

1条回答
爷、活的狠高调
2楼-- · 2019-05-03 23:36

This is not rocket science ...

Insert this in the place of the commented out code:

if (a == null) {
    return b == null ? 0 : -1;
} else if (b == null) {
    return 1;
} else 

This treats null as a smaller value than any non-null Double instance.


Your version is incorrect:

if ((a==null) || (b==null)) {return -1;}

This says "if a is null or b is null then a is smaller than b".

That leads to bogus relationships like

null < 1.0  AND 1.0 < null

null < null

This sort of thing causes the tree invariants to break when there are nulls in the set / map, and leads to inconsistent and unstable key ordering ... and worse.

The requirements for a valid compare method are set out in the javadocs. The mathematical version is that the method must define a total order over the domain of all possible input values.

查看更多
登录 后发表回答