Java:就地排序 ArrayList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7980078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: sorting an ArrayList in place
提问by NPE
In Java's standard library, is there a method that would allow one to sort an ArrayList
in place, i.e. using O(1)
extra storage?
在 Java 的标准库中,是否有一种方法可以让人们ArrayList
就地排序,即使用O(1)
额外的存储?
Collections.sort(List<T>)
does not fulfil this requirement since it
Collections.sort(List<T>)
不满足此要求,因为它
dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array.
将指定的列表转储到数组中,对数组进行排序,然后遍历列表,从数组中的相应位置重置每个元素。
If there's nothing in the standard library, what third-party libraries can be used to do this?
如果标准库中什么都没有,可以使用哪些第三方库来做到这一点?
采纳答案by Peter Lawrey
You can extract the underlying array (e.g. reflection) and perform a Arrays.sort(array, 0, list.size()) on it.
您可以提取底层数组(例如反射)并对其执行 Arrays.sort(array, 0, list.size()) 。
Java 7 does not copy the array in Arrays.sort() before sorting the array. In Java 6 it does which means that Collections.sort() in Java 6 actually copies the underlying array TWICE to perform the sort.
Java 7 在对数组进行排序之前不会复制 Arrays.sort() 中的数组。在 Java 6 中,这意味着 Java 6 中的 Collections.sort() 实际上复制了底层数组 TWICE 来执行排序。
回答by soulcheck
Collections.sort()
was made to work with any List implementation, and that's why it's not working in place (merging LinkedList in place is difficult and sacrifices stability).
Collections.sort()
被用于任何 List 实现,这就是它无法正常工作的原因(合并 LinkedList 很困难并且会牺牲稳定性)。
If you are really worried about sorting in-place you'll have to roll out your own sort funcion. It's not really worth your time unless your List is very long.
如果您真的担心就地排序,则必须推出自己的排序功能。除非你的 List 很长,否则它真的不值得你花时间。
Arrays.sort(Object[])
does the same mergesort and is called internally by Collections.sort()
(at least in openjdk)
Arrays.sort(Object[])
执行相同的归并排序并在内部调用Collections.sort()
(至少在 openjdk 中)
回答by GullerYA
As of Java 8 List
interface has default void sort(Comparator<? super E> c)
API, using which you can sort an instance in place.
从 Java 8 开始,List
接口具有默认void sort(Comparator<? super E> c)
API,您可以使用它就地对实例进行排序。
The list must be modifiable, iterable and its elements comparable to each other.
该列表必须是可修改的、可迭代的,并且其元素之间必须具有可比性。