2016-08-11 18 views
0
import java.util.ArrayList; 
import java.util.Calendar; 
import java.util.Date; 
import java.util.Iterator; 
import java.util.LinkedList; 
import java.util.List; 

    public class Sample { 

     Calendar cal = Calendar.getInstance(); 


     void getData(ArrayList<InvoiceBillingProjects> projectDataList){ 
      //System.out.println("start"); 
      long start = System.nanoTime(); 
      Iterator<InvoiceBillingProjects> itr = projectDataList.iterator(); 

      while(itr.hasNext()){ 
      // InvoiceBillingProjects ibpp = itr.next(); 
       itr.next().getDescription(); 
      } 
      /*for(int i=0;i<projectDataList.size();i++){ 
       projectDataList.get(i).getDescription(); 
      }*/ 
      long end = System.nanoTime(); 
      System.out.println(" time "+(end-start)); 
     } 


     public static void main(String arg[]) { 

      ArrayList<InvoiceBillingProjects> projectDataList = new ArrayList<InvoiceBillingProjects>(); 
      List<InvAssociateDetails> lt = new LinkedList<InvAssociateDetails>(); 
      for(int i=0;i<120000;i++){ 
       lt.add(new InvAssociateDetails()); 
       //new InvoiceBillingProjects().setAssociateList(lt); 

      } 
      for(int i=0;i<120000;i++){ 
       InvoiceBillingProjects ibp = new InvoiceBillingProjects(); 
       projectDataList.add(ibp); 
       ibp.setAssociateList(lt); 
      } 

      new Sample().getData(projectDataList); 
     } 
    } 

使用迭代器時,搜索整個列表時應比使用for循環時更快。上面的程序顯示了迭代開始和結束之間的時間更長。爲什麼使用迭代器需要更多時間?使用迭代器和for循環在列表中搜索:時間複雜度

回答

0

時間有什麼不同?這兩者應該差不多。請記住,查找ArrayList中的元素是恆定時間(O(1))。這兩種迭代方法都使用相同的查找。

+0

謝謝ArthuruhtrA,我知道了,因爲我期待的結果將會是這種情況,如果我使用列表的實現列表LinkedList和NOT數組列表。我的錯 :) –