[英]Java: sort List from index to index
對於數組,有一個特殊的函數用於從索引到索引對數組的一部分進行排序:
Arrays.sort(Object[] a, int fromIndex, int toIndex)
對於List< T>
還有一個排序功能
Collections.sort(List<T> list)
不幸的是,沒有接受fromIndex
和toIndex
參數的變體。
我知道我可以通過申請來解決這個問題
Arrays.sort
,然后將其轉換回 Listlist.subList(fromIndex, toIndex)
),對其進行排序並覆蓋舊列表條目但我希望有一種更漂亮的方法來做到這一點。
只需使用 .subList() 在主列表上獲得“支持”視圖,然后調用排序。 子列表是“直寫”,因此更改會反映在原始列表中。
List<Integer> foo = Arrays.asList(5,3,1,6,2,1);
Collections.sort(foo.subList(0, 3)); // sort first 3 elements
System.out.println(foo);
Collections.sort(foo.subList(3, 6)); // sort last 3 elements
System.out.println(foo);
輸出
[1, 3, 5, 6, 2, 1]
[1, 3, 5, 1, 2, 6]
您可以在原始列表上使用subList()
,然后subList()
列表進行排序,它會反映在您的原始列表中,而無需回寫。
將 fromIndex 到 toIndex 索引的列表條目復制到新列表(通過使用 list.subList(fromIndex, toIndex)),對其進行排序並覆蓋舊列表條目
不,當您調用 list.subList 時沒有對象副本。 函數 subList 創建一個由原始列表支持的視圖。 僅參考副本; 沒有實際的對象副本。
視圖上的任何操作(排序)都將反映在原始列表中。
public static void main(String[] args) throws Exception {
List<Integer> list = Arrays.asList(1, 9, 8 ,7, 2, 3, 4);
// [9, 8 ,7] => [7, 8, 9]
sortList(list, 1, 4);
System.out.println(list); // [1, 7, 8, 9, 2, 3, 4]
}
public static <T extends Comparable<T>> void sortList(
List<T> list, int fromIndex, int toIndex) {
Collections.sort(list.subList(fromIndex, toIndex));
}
查看 Oracle 文檔, Collections
和List
根本不包含此功能,就像Arrays
一樣。 如果我不得不在你的兩個建議之間做出選擇,我會使用List.subList(fromIndex, toIndex))
實現第二個。
這是文檔: http : //docs.oracle.com/javase/7/docs/api/java/util/List.html
http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.