默认构造器add

  1. import java.util.ArrayList;
  2. import java.util.LinkedList;
  3. import java.util.List;
  4. import java.util.UUID;
  5. public class Demo {
  6. public static void main(String[] args) {
  7. List<String> arrayList = new ArrayList<>();
  8. List<String> linkedList = new LinkedList<>();
  9. int length = 10000000;
  10. long start = System.currentTimeMillis();
  11. for (int i = 0; i < length; i++) {
  12. arrayList.add(UUID.randomUUID().toString());
  13. }
  14. long end = System.currentTimeMillis();
  15. System.out.println("ArrayList耗时:" + (end - start));
  16. start = System.currentTimeMillis();
  17. for (int i = 0; i < length; i++) {
  18. linkedList.add(UUID.randomUUID().toString());
  19. }
  20. end = System.currentTimeMillis();
  21. System.out.println("linkedList耗时:" + (end - start));
  22. }
  23. }

ArrayList耗时:10122 linkedList耗时:12241

分析:
ArrayList越大的时候扩容后就越大,添加元素以后扩容次数就越少。
LinkedList 每次都要创建节点 Node.

默认构造器指定位置add

  1. import java.util.ArrayList;
  2. import java.util.LinkedList;
  3. import java.util.List;
  4. import java.util.UUID;
  5. public class ClassLoaderDemo {e
  6. public static void main(String[] args) {
  7. List<String> arrayList = new ArrayList<>();
  8. List<String> linkedList = new LinkedList<>();
  9. int length = 100000;
  10. long start = System.currentTimeMillis();
  11. for (int i = 0; i < length; i++) {
  12. arrayList.add(0, UUID.randomUUID().toString());
  13. }
  14. long end = System.currentTimeMillis();
  15. System.out.println("ArrayList耗时:" + (end - start));
  16. start = System.currentTimeMillis();
  17. for (int i = 0; i < length; i++) {
  18. linkedList.add(0, UUID.randomUUID().toString());
  19. }
  20. end = System.currentTimeMillis();
  21. System.out.println("linkedList耗时:" + (end - start));
  22. }
  23. }

ArrayList耗时:1125 linkedList耗时:53

分析:
ArrayList 指定位置添加 后面的元素会复制向后移动一位。
LinkedList 只是节点指向变化。