兩個對象比較大小時出現的問題

錯誤案例

【現象描述】

兩個Integer類型的數據,進行大小比較,發現無法進行正確的比較

【錯誤代碼】

  Comparator<Integer> c = new Comparator<Integer>() {
    public int compare(Integer i1, Integer i2) {
      return i1 - i2;// 升序
    }
  };
  List<Integer> l = new ArrayList<Integer>();
  l.add(new Integer(-2000000000));
  l.add(new Integer(2000000000));
  Collections.sort(l, c);
  System.out.println(l);
  // [打印出來的結果:2000000000, -2000000000]

錯誤分析

先看看下面程序片斷:

int x = -2000000000;
int y = 2000000000;
/*
 * -2000000000 即 -(01110111001101011001010000000000)
 * 的補碼爲:                10001000110010100110110000000000
 * 
 * 計算過程使用豎式表示:
 * 10001000110010100110110000000000
 * 10001000110010100110110000000000
 * --------------------------------
 * 00010001100101001101100000000000
 * 
 * 計算結果溢出,結果爲294967296
 */
System.out.println(x - y);// 294967296

short, int, long減法和加法都可能出現數值溢出

正確用法

基於整型的比較器的實現一般使用如下的方式來比較:

Comparator<Integer> c = new Comparator<Integer>() {
  public int compare(Integer i1, Integer i2) {
    return (i1 < i2 ? -1 : (i1 == i2 ? 0 : 1));
  }
};
List<Integer> l = new ArrayList<Integer>();
l.add(new Integer(-2000000000));
l.add(new Integer(2000000000));
Collections.sort(l, c);
System.out.println(l);
// [打印出來的結果:-2000000000, 2000000000]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章