你写了这么多代码,有没考虑ArrayList和LinkedList底层数据结构的差异?
- import java.util.*;
- class HeimaCollectionDemo{
- public static void main (String []args){
- ArrayList a = new ArrayList();
- LinkedList l = new LinkedList();
- for(int x = 1 ;x<20000;x++ ){
- a.add(x+"");
- l.add(x+"");
- }
-
- String x = "15000";
- int y = 15000;
- System.out.println("ArrayList不指定角标时候添加元素");
- add(a,x);
- System.out.println("ArrayList删除一个不知道角标的元素");
- del(a,x);
- System.out.println("ArrayList向指定角标添加元素");
- add(a,y);
- System.out.println("ArrayList删除指定角标元素");
- del(a,y);
- System.out.println("=========================================");
- System.out.println("LinkedList不指定角标时候添加元素");
- add(l,x);
- System.out.println("LinkedList删除一个不知道角标的元素");
- del(l,x);
- System.out.println("LinkedList向指定角标添加元素");
- add(l,y);
- System.out.println("LinkedList删除指定角标元素");
- del(l,y);
-
- }
- public static void del(List list ,int index){
- if(list instanceof ArrayList )
- list = (ArrayList)list;
- else
- list = (LinkedList)list;
- long start = System.nanoTime();
- list.remove(index);
- long end = System.nanoTime();
- System.out.println( " "+ (end - start));
- }
- public static void add(List list ,int index){
- if(list instanceof ArrayList )
- list = (ArrayList)list;
- else
- list = (LinkedList)list;
- long start = System.nanoTime();
- list.add(index,1);
- long end = System.nanoTime();
- System.out.println( " "+ (end - start));
- }
-
-
- public static void del(List list ,String index){
- if(list instanceof ArrayList )
- list = (ArrayList)list;
- else
- list = (LinkedList)list;
- long start = System.nanoTime();
- list.remove(index);
- long end = System.nanoTime();
- System.out.println( " "+ (end - start));
- }
- public static void add(List list ,String index){
- if(list instanceof ArrayList )
- list = (ArrayList)list;
- else
- list = (LinkedList)list;
- long start = System.nanoTime();
- list.add(index);
- long end = System.nanoTime();
- System.out.println( " "+ (end - start));
- }
-
-
- }
复制代码 |