[英]Collections.sort not give expected
我正在嘗試根據該索引處的值對數組的索引進行排序。 例如。 [0,2,2,1] 將給出 [0,2,3,1] 或 [0,3,2,1]
List<Integer> index_map = new LinkedList(Arrays.asList(0,1,2,3));
final int[] sizes = {0,2,1,1};
Collections.sort(index_map, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return sizes[a] < sizes[b] ? -1 : 1;
}
});
System.out.println(Arrays.toString(sizes));
System.out.println(index_map);
但是,使用 Collections.sort() 和定義的比較器給出 [0,3,1,2] 。 有人能告訴我為什么 output 是這樣的嗎?是否有更好的方法來實現目標? 謝謝
FIX:您錯過了相等值的情況並且不重新實現比較代碼,直接使用方法Integer.compare
:
List<Integer> index_map = new LinkedList(Arrays.asList(0,1,2,3));
final int[] sizes = {0,2,1,1};
Collections.sort(index_map, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return Integer.compare(sizes[a],sizes[b]);
}
});
改進:可以用它的lambda版本來減少
Collections.sort(index_map, (a, b) -> Integer.compare(sizes[a], sizes[b]));
最佳:使用 compareInt 允許僅指定用於比較的值,您也可以直接在列表上調用sort
:
index_map.sort(Comparator.comparingInt(a -> sizes[a]));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.