2012-03-07 49 views
4

此自定義的Valuecomparator通過其值對TreeMap進行排序。但是,在搜索TreeMap是否具有某個鍵時,它不能容忍nullpointexception。我如何修改比較器來處理零點?使TreeMap Comparator容忍null

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


} 

回答

6

這不是火箭科學...

插入此在的註釋掉的代碼的地方:

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

這把null作爲比任何非空Double較小的值實例。


你的版本不正確:

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

這是說 「如果爲空或b爲null,則A比B小」。

這導致虛假的關係就像

null < 1.0 AND 1.0 < null 

null < null 

這樣的事情會導致樹不變量當有一組/圖空打破,並導致矛盾和不穩定鍵排序......更糟。

要求有效compare方法列在javadocs。數學形式是該方法必須在所有可能的輸入值的域上定義一個total order

+0

啊,是的,使它小於非零! 我試過'if((a == null)||(b == null)){return -1;}'。但是這並不能正確地對地圖進行排序。爲什麼? – alvas 2012-03-07 07:12:17

+0

因爲它違反了'x.equals(x)''時'comparator.compare(x,x)== 0'的約束,特別是當'x == null'時。 – 2012-03-07 11:54:12