【发布时间】:2013-08-12 17:41:01
【问题描述】:
我正在使用ArrayList 并尝试在ArrayList 的开头添加new object 的预填充ArrayList,并准备好3000000 记录。
据我所知,它将在第一个索引处添加新对象并将下面的所有记录移动到它们之前的位置。每次我将新对象添加到该数组列表时都会发生这种情况。意味着执行时间应该相同(可能会发生一些变化)。
但是当我添加新记录时,它会显示 0 和某个时间 15。
这是我的程序
package com.rais;
import java.util.ArrayList;
import java.util.List;
public class ArrayListTest {
public static List<String> arrList = new ArrayList<String>();
static {
for (int i = 0; i < 3000000; i++) {
arrList.add("Hello"+i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
long startTime = System.currentTimeMillis();
arrList.add(0,"Rais"+i);
long endTime = System.currentTimeMillis();
System.out.println("Total execution time ="+(endTime-startTime));
}
}
}
这是该程序的输出。
Total execution time =0
Total execution time =0
Total execution time =15
Total execution time =0
Total execution time =0
我很困惑为什么它显示 0 。每次应该显示 15 或接近 15,但不应该显示 0。
【问题讨论】:
-
在某些旧版本的 Windows 上,此计时器的分辨率很差。我建议您使用 System.nanoTime() 并且由于代码在运行 10,000 次之前不会预热,因此我将忽略前 12,000 次运行。
标签: java performance collections arraylist indexing