Java 为什么ArrayList';s排序方法比数组快';在爪哇?

Java 为什么ArrayList';s排序方法比数组快';在爪哇?,java,arrays,sorting,arraylist,Java,Arrays,Sorting,Arraylist,下面代码的目标是对300000整数进行排序。我发现ArrayList的sort()的持续时间小于Arrays的sort()。在内部,它们使用相同的算法进行排序。ArrayList使用数组的sort()对其元素数据进行排序 public class EasySort { public static void main(String args[]) { // Read data from file, number split by "," FileReader

下面代码的目标是对300000整数进行排序。我发现ArrayList的sort()的持续时间小于Arrays的sort()。在内部,它们使用相同的算法进行排序。ArrayList使用数组的sort()对其元素数据进行排序

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));
    }
}
公共类EasySort{
公共静态void main(字符串参数[]){
//从文件中读取数据,数字以“,”分隔
FileReader fr=null;
试一试{
fr=新文件读取器(“testdata2.txt”);
}catch(filenotfounde异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
BufferedReader BufferedReader=新的BufferedReader(fr);
字符串行=null;
试一试{
line=bufferedReader.readLine();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
//使用split方法生成字符串数组以保存数字
String[]strArray=line.split(“,”);
//将字符串数组转换为ArrayList
ArrayList integerList=新的ArrayList();
用于(字符串str:strArray){
add(Integer.parseInt(str));
}
//按数组列表排序
长t0=System.currentTimeMillis();
integerList.sort((p1,p2)->(p1.intValue()p2.intValue()?1:0));
long t1=System.currentTimeMillis();
System.out.println(“ArrayList排序持续时间:”+(t1-t0));
//将字符串数组转换为整数数组
整数[]整数数组=新整数[strArray.length];
int i=0;
用于(字符串str:strArray){
integerArray[i++]=Integer.parseInt(str);
}
//按数组排序
t0=System.currentTimeMillis();
sort(integerArray,((p1,p2)->(p1.intValue()p2.intValue()?1:0));
t1=System.currentTimeMillis();
System.out.println(“数组持续时间:”+(t1-t0));
}
}
结果如下:
ArrayList排序持续时间:211
阵列持续时间: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++;
    }
@覆盖
@抑制警告(“未选中”)

public void sort(Comparator它们应该是相同的,我不知道为什么会有不同的结果。下面是我的代码,我的时间几乎相同。For
T[]
ArrayList
都将调用
Arrays.sort(T[],…)
,然后使用合并排序或tim排序

Random rand = new Random();
Integer[] array = new Integer[300000];
for (int i = 0; i < array.length; i++)
    array[i] = rand.nextInt(array.length);  
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array));    

long a = System.currentTimeMillis();
Arrays.sort(array, 0 ,array.length);
long b = System.currentTimeMillis();
list.sort(null);
long c = System.currentTimeMillis();

System.out.println(b - a);
System.out.println(c - b);
Random rand=new Random();
整数[]数组=新整数[300000];
for(int i=0;i
这是一个热身问题-但我不知道确切原因

使用此代码:

public void test() {
    Integer[] a = randomData(10000000);

    ArrayList<Integer> integerList = new ArrayList<>();
    for (Integer i : a) {
        integerList.add(i);
    }

    long t0, t1;
    //Sort by ArrayList
    t0 = System.currentTimeMillis();
    integerList.sort(((p1, p2) -> (p1.intValue() < p2.intValue() ? -1 : p1.intValue() > p2.intValue() ? 1 : 0)));
    t1 = System.currentTimeMillis();
    System.out.println("ArrayList duration:" + (t1 - t0));


    //Sort by Arrays
    Integer[] integerArray = Arrays.copyOf(a, a.length);
    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));

}

Random r = new Random(System.currentTimeMillis());

private Integer[] randomData(int n) {
    Integer[] a = new Integer[n];
    for (int i = 0; i < n; i++) {
        a[i] = r.nextInt();
    }
    return a;
}
公共无效测试(){
整数[]a=随机数据(10000000);
ArrayList integerList=新的ArrayList();
for(整数i:a){
整数列表。添加(i);
}
长t0,t1;
//按数组列表排序
t0=System.currentTimeMillis();
integerList.sort((p1,p2)->(p1.intValue()p2.intValue()?1:0));
t1=System.currentTimeMillis();
System.out.println(“ArrayList持续时间:”+(t1-t0));
//按数组排序
整数[]integerArray=Arrays.copyOf(a,a.length);
t0=System.currentTimeMillis();
排序(integerArray,((p1,p2)->(p1.intValue()p2.intValue()?1:0));
t1=System.currentTimeMillis();
System.out.println(“数组持续时间:”+(t1-t0));
}
Random r=新的Random(System.currentTimeMillis());
私有整数[]随机数据(整数n){
整数[]a=新整数[n];
对于(int i=0;i
将这两种类型转换成不同的顺序:

阵列持续时间:4209

ArrayList持续时间:4570

ArrayList持续时间:6776

阵列持续时间:4684

因此,如果先排序
ArrayList
,则需要更长的时间

因此@AndyTurner的评论是正确的-请参阅


Java 8-Windows 10

这是我使用Java 8尝试的东西。请注意,有一个数组是
int
s,一个
Integer
s数组,而
列表是
Integer
s。此外,
Integer
数组是使用
数组.parallelSort()
排序的

import java.util.*;
导入java.util.stream.*;
公共类测试排序{
公共静态void main(字符串[]args){
长t0=0L;
长t1=0L;
//运行此过程10次
对于(int i=1;i<11;i++){
//创建一个整数数组和一个填充了随机数的整数列表
int[]intArray=IntStream.generate(()->new Random().nextInt())
.限额(300_000)
.toArray();
整数[]integerArray=IntStream.generate(()->new Random().nextInt())
.限额(300_000)
.boxed()
.toArray(n->新整数[n]);
整数[]integerArrayP=IntStream.generate(()->new Random().nextInt())
.限额(300_000)
.boxed()
.toArray(n->新整数[n]);
List intList=IntStream.generate(()->new Random().nextInt())
.限额(300_000)
.boxed()
.collect(收集器.toCollection(ArrayList::new));
//对列表和数组进行排序
t0=System.currentTimeMillis();
intList.sort(null);
t1=System.currentTimeMillis();
系统输出打印LN(i)
import java.util.*;
import java.util.stream.*;
public class TestingSorts {
    public static void main(String[] args) {
        long t0 = 0L;
        long t1 = 0L;
        // Run this procedure 10 times
        for (int i = 1; i < 11; i++) {
            // Create an int array and Integer List filled with random numbers
            int [] intArray = IntStream.generate(() -> new Random().nextInt())
                        .limit(300_000)
                        .toArray();
            Integer [] integerArray = IntStream.generate(() -> new Random().nextInt())
                        .limit(300_000)
                        .boxed()
                        .toArray(n -> new Integer[n]);
            Integer [] integerArrayP = IntStream.generate(() -> new Random().nextInt())
                        .limit(300_000)
                        .boxed()
                        .toArray(n -> new Integer[n]);
            List<Integer> intList = IntStream.generate(() -> new Random().nextInt())
                        .limit(300_000)
                        .boxed()
                        .collect(Collectors.toCollection(ArrayList::new));
            // Sort the List and the arrays
            t0 = System.currentTimeMillis();
            intList.sort(null);
            t1 = System.currentTimeMillis();
            System.out.println(i + ") ArrayList<Integer> sort duration: " + (t1 - t0));
            t0 = System.currentTimeMillis();
            Arrays.sort(integerArray, Comparator.naturalOrder());
            t1 = System.currentTimeMillis();
            System.out.println(i + ") Integer[ ] sort duration: " + (t1 - t0));
            t0 = System.currentTimeMillis();
            Arrays.parallelSort(integerArrayP, Comparator.naturalOrder());
            t1 = System.currentTimeMillis();
            System.out.println(i + ") Integer[ ] PARALLEL sort duration: " + (t1 - t0));
            t0 = System.currentTimeMillis();
            Arrays.sort(intArray);
            t1 = System.currentTimeMillis();
            System.out.println(i + ") int[ ] sort duration: " + (t1 - t0));
        }
    }
}
1) ArrayList<Integer> sort duration: 200
1) Integer[ ] sort duration: 424
1) Integer[ ] PARALLEL sort duration: 414
1) int[ ] sort duration: 136
2) ArrayList<Integer> sort duration: 143
2) Integer[ ] sort duration: 101
2) Integer[ ] PARALLEL sort duration: 56
2) int[ ] sort duration: 33
3) ArrayList<Integer> sort duration: 124
3) Integer[ ] sort duration: 118
3) Integer[ ] PARALLEL sort duration: 96
3) int[ ] sort duration: 42
4) ArrayList<Integer> sort duration: 108
4) Integer[ ] sort duration: 102
4) Integer[ ] PARALLEL sort duration: 92
4) int[ ] sort duration: 57
5) ArrayList<Integer> sort duration: 142
5) Integer[ ] sort duration: 113
5) Integer[ ] PARALLEL sort duration: 118
5) int[ ] sort duration: 31
6) ArrayList<Integer> sort duration: 113
6) Integer[ ] sort duration: 103
6) Integer[ ] PARALLEL sort duration: 58
6) int[ ] sort duration: 32
7) ArrayList<Integer> sort duration: 115
7) Integer[ ] sort duration: 116
7) Integer[ ] PARALLEL sort duration: 57
7) int[ ] sort duration: 33
8) ArrayList<Integer> sort duration: 115
8) Integer[ ] sort duration: 115
8) Integer[ ] PARALLEL sort duration: 58
8) int[ ] sort duration: 31
9) ArrayList<Integer> sort duration: 114
9) Integer[ ] sort duration: 101
9) Integer[ ] PARALLEL sort duration: 52
9) int[ ] sort duration: 32
10) ArrayList<Integer> sort duration: 113
10) Integer[ ] sort duration: 114
10) Integer[ ] PARALLEL sort duration: 57
10) int[ ] sort duration: 32