2017-03-14 126 views
1

不像其他異常場景我見過,我不斷髮生的異常發生在for循環我下面評論//它出錯//。在我的實現中,列表partialR在迭代時不會改變,所以我非常困惑。爲什麼我在高級for循環中獲取java.util.ConcurrentModificationException?

public class Solution { 
    public List<List<Integer>> permute(int[] nums) { 
     List<List<Integer>> result = new ArrayList<>(); 
     result.add(new ArrayList<Integer>()); 
     return permute(nums, 0, result); 
    } 

    public List<List<Integer>> permute(int[] nums, int i, List<List<Integer>> result){ 
     if (i == nums.length){ 
      return result; 
     } 
     int num = nums[i]; 
     List<List<Integer>> partialR = permute(nums, i+1, result); 
     System.out.println("partialR"+partialR); 
     for (List<Integer> t : partialR){***//where it goes wrong//*** 
      System.out.println("t"+t); 
      for (int j=0; j <= t.size(); j++){ 
       System.out.println("j="+j); 
       List<Integer> subs = insert(t,num,j); 
       result.add(subs); 
       System.out.println("result"+result); 
      } 
     } 
     System.out.println("result"); 
     return result; 
    } 
    public List<Integer> insert(List<Integer> t, int num, int j){ 
     List<Integer> temp = new ArrayList<>();  
     if (j == 0){ 
      temp.add(num); 
      temp.addAll(t); 
      System.out.println("temp"+temp); 
      return temp; 
     }else if(j == t.size()){ 
      temp.addAll(t); 
      temp.add(num); 
      return temp; 
     } 
     List<Integer> temp1 = new ArrayList<Integer> (t.subList(j,t.size()-1)); 
     List<Integer> temp2 = new ArrayList<Integer> (t.subList(0,j-1)); 
     temp.addAll(temp1); 
     temp.add(num); 
     temp.addAll(temp2); 
     return temp; 
    } 
} 
+0

*在我的實現,列表partialR不會改變,而我迭代*。它可能看起來像這樣,但'partialR'引用與'result'相同的列表,你正在修改它。 – shmosel

回答

2

您傳遞resultpermute,並返回result。 所以,當你這樣做:

List<List<Integer>> partialR = permute(nums, i+1, result); 

現在partialRresult了。 然後當你用for (List<Integer> t : partialR), 迭代它時,當你做result.add(subs)時,你修改result。 因此,實際上,您在迭代時正在修改result, ,這是失敗快速在Java中迭代器的行爲所不允許的。 (您可以在ConcurrentModificationException的Javadoc瞭解更多關於這一點。)

您可以通過在這裏創建一個新的ArrayList解決這個問題:

List<List<Integer>> partialR = new ArrayList<>(permute(nums, i + 1, result)); 

還有一些其他的錯誤太多,無關的併發修改。 在insert中,創建temp1temp2的值的範圍不正確。更正和簡化,你可以寫:

List<Integer> temp1 = t.subList(j, t.size()); 
List<Integer> temp2 = t.subList(0, j); 
+0

非常感謝,這一切都奏效了。 –

相關問題