2013-07-31 37 views
0

我用簡單的comperator並獲得異常,不知道該怎麼辦Java集合排序問題

這是我如何打電話:

try { 
    Collections.sort(this.closePositions, new PositionComperator()); 
} 
catch(Exception e) { 
    e.printStackTrace(); 
} 

這是comperator:

public class PositionComperator implements Comparator<DataResponse> { 

    @Override 
    public int compare(DataResponse pos1, DataResponse pos2) { 

     if (pos1.openTime >= pos2.openTime) { 
      return 1; 
     } 
     else { 
      return -1; 
     }// returning 0 would merge keys 

    } 

    } 

這是個例外:

java.lang.IllegalArgumentException: Comparison method violates its general contract! 
at java.util.TimSort.mergeLo(Unknown Source) 
at java.util.TimSort.mergeAt(Unknown Source) 
at java.util.TimSort.mergeCollapse(Unknown Source) 
at java.util.TimSort.sort(Unknown Source) 
at java.util.TimSort.sort(Unknown Source) 
at java.util.Arrays.sort(Unknown Source) 
at java.util.Collections.sort(Unknown Source) 
at GTTask.RefreshIdentityHistory.call(RefreshIdentityHistory.java:59) 
at GTTask.RefreshIdentityHistory.call(RefreshIdentityHistory.java:1) 
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source) 
at java.util.concurrent.FutureTask.run(Unknown Source) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) 
at java.lang.Thread.run(Unknown Source) 
+0

'sort'不能引起元素得到合併。雖然如果你要使用Set,那將是一個不同的故事。 – Dukeling

+0

你可以提供PositionComperator的代碼 – Ruju

回答

1

你得到這個錯誤的原因是,當它整理兩個項目,他們改變順序。你也應該包括它是平等的情況。

最好這樣做:

return po1.openTime - pos2.opentime; 

或做

if (pos1.openTime > pos2.openTime) { 
    return 1; 
} 
else if (pos1.openTime < pos2.openTime) { 
    return -1; 
} else { 
    return 0; 
} 
+0

什麼是「返回0」會導致什麼? – user502967

+0

這意味着他們是平等的,他們不會被排序。查看比較方法的java文檔。 – Knubo

+0

謝謝!它正在工作 – user502967

2

如果兩個值xy具有相同openTime,然後compare(x, y)compare(y, x)都將返回1,違反的compare合同:

實現程序必須確保sgn(compare(x, y)) == -sgn(compare(y, x))所有xy

您還沒有確定。

你需要考慮你希望在openTime值相同的情況發生什麼 - 要麼返回0,或者有一些一致概念其值應該還是先等。例如,你可以執行一些次級比較嗎?

+0

但條件我使用「> =」 - 它不解決這個問題嗎? – user502967

+0

@ user502967:不,正是我給出的原因:如果這兩個值相等,那麼在比較兩種值時您會得到1。看看'比較'的合約。 –

+0

感謝您的解釋:))) – user502967

1

你可以使用treeSet。 İt是爲你排序。並且有比較方法。例如

TreeSet<Double> sortedSet = new TreeSet<Double>(); 

例如比較一下

TreeSet<Double> set = new TreeSet<Rock>(new Comparator<Double>() 
public int compare(Double a, Double b){ 
       return a.value - b.value; 
      } 
     } 
+0

爲什麼要在列表上使用樹排序? – user502967

+0

你可以看看這個話題爲什麼你應該使用treeset。 Treeset直接對它進行排序和比較,你不需要另一種方法,你可以看到更簡單。 http://stackoverflow.com/questions/1463284/hashset-vs-treeset – user2583040