2013-02-17 113 views
0

由於某些原因,我的方法中的所有for-each循環都被完全忽略,我無法弄清楚原因。這裏是我的代碼:對於每個循環都不執行

private static boolean notUsed(ArrayList<Integer> check, ArrayList<ArrayList<Integer>> used) 
    { 
    boolean c1 = false; 
    boolean c2 = true; 
    for (ArrayList<Integer> item : used) // Not executed 
    { 
     System.out.println("It works!"); 
     Collections.sort(item); 
     Collections.sort(check); 
     if (check.equals(item)) c1 = true; 
    } 
    ArrayList<Integer> existing = new ArrayList<Integer>(); 
    for (int item : check) 
    { 
     for (int exists : existing) // Not executed 
     { 
     if (exists == item) 
     { 
      c2 = false; 
      break; 
     } 
     else existing.add(item); 
     } 
     if (c2 == false) break; 
    } 
    if (c1 && c2) return true; 
    else return false; 
    } 

我已經持續了它在過去的15分鐘,看不出爲什麼代碼拒絕與循環的內容費心。事實上,我甚至都不知道java可以在現在之前避免執行循環。我錯過了明顯的東西嗎?

+0

您是否嘗試過在你的foreach循環變化的int整數?它們是有區別的。一個是原始的,一個是對象,所以這可能是你的問題。 – 2013-02-17 03:21:39

+0

ArrayList的大小是多少? – afrischke 2013-02-17 03:22:23

+0

當你說(ArrayList 項目:使用)//未執行 – smk 2013-02-17 03:23:18

回答

2

你做一個新的ArrayList

ArrayList<Integer> existing = new ArrayList<Integer>(); 

裏面是空的。

當foreach運行時,它沒有什麼可以迭代。因此,您的「未執行」評論完全有效。

但是,第一個循環取決於傳遞的是什麼。讓一些print statemtents找出列表的大小。最有可能的是,也是0,這也是導致循環被「跳過」的原因。

+0

啊,那麼有問題,然後......讓我解決這個問題,看看它是否工作。 – Thrfoot 2013-02-17 03:26:25

+1

好的,讓它工作。謝謝! – Thrfoot 2013-02-17 03:37:26

3

是的,你錯過了一些明顯的東西。

如果這些循環沒有執行,那麼在傳遞給例程的參數中沒有元素。

1

大小used必須是0,第二個循環不執行,因爲existing是一個新的ArrayList和它的規模肯定是0

0

這裏工作code..this會給你的想法。正如其他mentioned..there也不會有任何元素迭代...因爲我跑了下面的代碼,併爲每個循環的作品...

import java.util.ArrayList; 
import java.util.Collections; 


public class Test1 { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     ArrayList<ArrayList<Integer>> used = new ArrayList<ArrayList<Integer>>(); 
     ArrayList<Integer>item = new ArrayList<Integer>(); 
     item.add(1); 
     used.add(item); 
     notUsed(item,used); 
    } 

    private static boolean notUsed(ArrayList<Integer> check, ArrayList<ArrayList<Integer>> used) 
     { 
     boolean c1 = false; 
     boolean c2 = true; 
     for (ArrayList<Integer> item : used) // Not executed 
     { 
      System.out.println("It works!"); 
      Collections.sort(item); 
      Collections.sort(check); 
      if (check.equals(item)) c1 = true; 
     } 
     ArrayList<Integer> existing = new ArrayList<Integer>(); 
     for (int item : check) 
     { 
      for (int exists : existing) // Not executed 
      { 
      if (exists == item) 
      { 
       c2 = false; 
       break; 
      } 
      else existing.add(item); 
      } 
      if (c2 == false) break; 
     } 
     if (c1 && c2) return true; 
     else return false; 
     } 

}