我一直在查看 java.util.Arrays 的源代码,在排序时它总是指数组的长度(对于 ArrayList,我假设指的是 E[] 数据的长度( transient ) field 。 但它实际上不应该指的是大小字段,因为它们并不总是彼此相等。
最佳答案
when sorting it always refers to the length of the array
不,没有。对于每种数据类型,都有 Arrays.sort
的重载它接受 fromIndex
和toIndex
参数,指定要排序的数组的确切部分,例如 Arrays.sort(Object[] a, int fromIndex, int toIndex, Comparator<? super T> c)
.
这是 ArrayList.sort
调用的方法:
public void sort(Comparator<? super E> c) {
final int expectedModCount = modCount;
Arrays.sort((E[]) elementData, 0, size, c);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
ArrayList
通过自己的size
变量直接传递给排序方法。
对于List
它不会覆盖 its sort
method ,default implementation首先将内容转储到临时数组并对其进行排序:
The default implementation obtains an array containing all elements in this list, sorts the array, and iterates over this list resetting each element from the corresponding position in the array. (This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.)
default void sort(Comparator<? super E> c) {
Object[] a = this.toArray();
Arrays.sort(a, (Comparator) c);
ListIterator<E> i = this.listIterator();
for (Object e : a) {
i.next();
i.set((E) e);
}
}
从Java 8开始,旧方法 Collections.sort(list)
只是调用list.sort(null)
.
关于java - java.util.Arrays 如何处理 ArrayList 的排序(长度与大小)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43172027/