默认构造器add
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
public class Demo {
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
int length = 10000000;
long start = System.currentTimeMillis();
for (int i = 0; i < length; i++) {
arrayList.add(UUID.randomUUID().toString());
}
long end = System.currentTimeMillis();
System.out.println("ArrayList耗时:" + (end - start));
start = System.currentTimeMillis();
for (int i = 0; i < length; i++) {
linkedList.add(UUID.randomUUID().toString());
}
end = System.currentTimeMillis();
System.out.println("linkedList耗时:" + (end - start));
}
}
ArrayList耗时:10122 linkedList耗时:12241
分析:
ArrayList越大的时候扩容后就越大,添加元素以后扩容次数就越少。
LinkedList 每次都要创建节点 Node.
默认构造器指定位置add
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
public class ClassLoaderDemo {e
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
int length = 100000;
long start = System.currentTimeMillis();
for (int i = 0; i < length; i++) {
arrayList.add(0, UUID.randomUUID().toString());
}
long end = System.currentTimeMillis();
System.out.println("ArrayList耗时:" + (end - start));
start = System.currentTimeMillis();
for (int i = 0; i < length; i++) {
linkedList.add(0, UUID.randomUUID().toString());
}
end = System.currentTimeMillis();
System.out.println("linkedList耗时:" + (end - start));
}
}
ArrayList耗时:1125 linkedList耗时:53
分析:
ArrayList 指定位置添加 后面的元素会复制向后移动一位。
LinkedList 只是节点指向变化。