ArrayList和LinkedList比较
(1)元素新增性能比较
在新增操作时,ArrayList和LinkedList的效率如何,下面来进行测试。
public class ListTest {
//迭代次数
public static int ITERATION_NUM = 100000;
public static void main(String[] args) throws InterruptedException {
insertPerformanceCompare();
}
//新增性能比较
public static void insertPerformanceCompare() throws InterruptedException {
Thread.sleep(5000);
System.out.println("LinkedList新增测试开始");
long start = System.nanoTime();
List<Integer> linkedList = new LinkedList<Integer>();
for (int x = 0; x < ITERATION_NUM; x++) {
linkedList.add(x);
}
long end = System.nanoTime();
System.out.println(end - start);
System.out.println("-----分割线-----");
System.out.println("ArrayList新增测试开始");
start = System.nanoTime();
List<Integer> arrayList = new ArrayList<Integer>();
for (int x = 0; x < ITERATION_NUM; x++) {
arrayList.add(x);
}
end = System.nanoTime();
System.out.println(end - start);
}
}
打印结果为:
LinkedList新增测试开始
6084500
-----分割线-----
ArrayList新增测试开始
2738000
可以看出,ArrayList在新增元素时的效率要高于LinkedList。
(2)元素获取性能比较
public class ListTest1 {
public static int ITERATION_NUM = 100000;
public static void main(String[] args) throws InterruptedException {
getPerformanceCompare();
}
//获取性能比较
public static void getPerformanceCompare() throws InterruptedException {
Thread.sleep(5000);
//填充ArrayList集合
List<Integer> arratList = new ArrayList<Integer>();
for (int x = 0; x < ITERATION_NUM; x++) {
arratList.add(x);
}
//填充LinkedList集合
List<Integer> linkedList = new LinkedList<Integer>();
for (int x = 0; x < ITERATION_NUM; x++) {
linkedList.add(x);
}
//创建随机数对象
Random random = new Random();
System.out.println("LinkedList获取测试现在开始");
long start = System.nanoTime();
for (int x = 0; x < ITERATION_NUM; x++) {
int j = random.nextInt(x + 1);
int k = linkedList.get(j);
}
long end = System.nanoTime();
System.out.println(end - start);
System.out.println("-----分割线-----");
System.out.println("ArrayList获取测试现在开始");
start = System.nanoTime();
for (int x = 0; x < ITERATION_NUM; x++) {
int j = random.nextInt(x + 1);
int k = arratList.get(j);
}
end = System.nanoTime();
System.out.println(end - start);
}
}
打印结果为:
LinkedList获取测试现在开始
2789422500
-----分割线-----
ArrayList获取测试现在开始
3429300
可以看出ArrayList在随机访问方面表现比LinkedList好很多。