以下代码的目标是对30万个整数进行排序。我发现ArrayList的sort()方法所需时间比Arrays的sort()方法少。在内部,它们都使用相同的算法进行排序。ArrayList使用Arrays的sort()方法来对其元素数据进行排序。
结果如下:
ArrayList排序时间:211毫秒
Arrays排序时间:435毫秒
我检查了ArrayList的源代码,它在自己的排序方法中使用了Arrays.sort()。
所以,在我看来,我的代码应该显示相同的持续时间。但是我尝试了很多次,结果都类似。发生了什么?
Java 版本:8 操作系统:Windows 7
public class EasySort {
public static void main(String args[]) {
// Read data from file, number split by ","
FileReader fr = null;
try {
fr = new FileReader("testdata2.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader bufferedReader=new BufferedReader(fr);
String line=null;
try {
line=bufferedReader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// use split method to generate a String array to save numbers
String[] strArray=line.split(",");
//Convert string array to ArrayList<Integer>
ArrayList<Integer> integerList=new ArrayList<>();
for(String str:strArray){
integerList.add(Integer.parseInt(str));
}
//Sort by ArrayList
long t0=System.currentTimeMillis();
integerList.sort(((p1,p2)->(p1.intValue()<p2.intValue()?-1:p1.intValue()>p2.intValue()?1:0)));
long t1=System.currentTimeMillis();
System.out.println("ArrayList Sort duration:"+(t1-t0));
//Convert string array to Integer array
Integer[] integerArray=new Integer[strArray.length];
int i=0;
for(String str:strArray){
integerArray[i++]=Integer.parseInt(str);
}
//Sort by Arrays
t0=System.currentTimeMillis();
Arrays.sort(integerArray, ((p1,p2)->(p1.intValue()<p2.intValue()?-1:p1.intValue()>p2.intValue()?1:0)));
t1=System.currentTimeMillis();
System.out.println("Arrays duration:"+(t1-t0));
}
}
结果如下:
ArrayList排序时间:211毫秒
Arrays排序时间:435毫秒
我检查了ArrayList的源代码,它在自己的排序方法中使用了Arrays.sort()。
@Override
@SuppressWarnings("unchecked")
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++;
}
所以,在我看来,我的代码应该显示相同的持续时间。但是我尝试了很多次,结果都类似。发生了什么?
Java 版本:8 操作系统:Windows 7
List<Integer>
可以在没有比较器的情况下进行排序(Integer
已经实现了Comparable
); 因此,integerList.sort(null)
就可以了。那么,是否需要创建Integer [] integerArray
?使用原始int
数组;并使用Arrays.sort(intArray)
。你可能会看到不同的结果。 - prasad_ArrayList<Integer>
和Integer[]
,它们几乎是相同的时间。 - zhh