有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使树映射比较器容忍空值

这个定制的Valuecomparator根据树形图的值对其进行排序。但在搜索树映射是否有某个键时,它不能容忍nullpointexception。如何修改比较器以处理空值

    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) 个答案

  1. # 1 楼答案

    这不是火箭科学

    在注释掉的代码处插入:

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

    这将null视为比任何非空Double实例更小的值


    您的版本不正确:

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

    这表示“如果a为空或b为空,则a小于b”

    这会导致虚假的关系,比如

    null < 1.0  AND 1.0 < null
    
    null < null
    

    当集合/映射中存在空值时,这种情况会导致树不变量中断,并导致不一致和不稳定的键顺序。。。更糟

    有效compare方法的要求javadocs中列出。数学版本是,该方法必须在所有可能输入值的域上定义total order