我知道get()
中ArrayList
操作所花费的时间是O(1),但是我注意到第一个元素总是比其他元素要多或相等。我试过100次。我知道这并不重要,因为差异在纳秒内,但想知道是否有任何逻辑解释或它只是随机。
这是我的节目:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ListTest {
public static void main(String[] args) throws IOException {
for (int i = 1; i <= 20; i++) {
System.out.println("============== Iteration ======= "+i);
List<String> list = new ArrayList<String>();
for (int j = 0; j < 50000; j++) {
list.add(j + "");
}
long t1 = System.nanoTime();
list.get(0);
long t2 = System.nanoTime();
System.out.println("time (0) :: " + (t2 - t1));
t1 = System.nanoTime();
list.get(20000);
t2 = System.nanoTime();
System.out.println("time (20000) :: " + (t2 - t1));
t1 = System.nanoTime();
list.get(49000);
t2 = System.nanoTime();
System.out.println("time (49000) :: " + (t2 - t1));
}
}
}
输出:
============== Iteration ======= 1
time (0) :: 12000
time (20000) :: 1000
time (49000) :: 0
============== Iteration ======= 2
time (0) :: 17000
time (20000) :: 14000
time (49000) :: 16000
============== Iteration ======= 3
time (0) :: 2000
time (20000) :: 0
time (49000) :: 0
============== Iteration ======= 4
time (0) :: 3000
time (20000) :: 1000
time (49000) :: 0
============== Iteration ======= 5
time (0) :: 16000
time (20000) :: 8000
time (49000) :: 8000
============== Iteration ======= 6
time (0) :: 2000
time (20000) :: 0
time (49000) :: 0
============== Iteration ======= 7
time (0) :: 1000
time (20000) :: 1000
time (49000) :: 0
============== Iteration ======= 8
time (0) :: 4000
time (20000) :: 0
time (49000) :: 1000
============== Iteration ======= 9
time (0) :: 2000
time (20000) :: 0
time (49000) :: 0
============== Iteration ======= 10
time (0) :: 1000
time (20000) :: 1000
time (49000) :: 1000
============== Iteration ======= 11
time (0) :: 2000
time (20000) :: 0
time (49000) :: 0
============== Iteration ======= 12
time (0) :: 2000
time (20000) :: 0
time (49000) :: 0
============== Iteration ======= 13
time (0) :: 2000
time (20000) :: 1000
time (49000) :: 1000
============== Iteration ======= 14
time (0) :: 1000
time (20000) :: 0
time (49000) :: 0
============== Iteration ======= 15
time (0) :: 2000
time (20000) :: 0
time (49000) :: 0
============== Iteration ======= 16
time (0) :: 2000
time (20000) :: 0
time (49000) :: 0
============== Iteration ======= 17
time (0) :: 2000
time (20000) :: 0
time (49000) :: 0
============== Iteration ======= 18
time (0) :: 1000
time (20000) :: 1000
time (49000) :: 1000
============== Iteration ======= 19
time (0) :: 1000
time (20000) :: 1000
time (49000) :: 0
============== Iteration ======= 20
time (0) :: 2000
time (20000) :: 0
time (49000) :: 0