2013-08-16 33 views
0

我試圖創建一個包含0和1的所有可能組合的字符串數組的列表,四維。也就是說,[0,0,0,0]是一個組合,[0,0,0,1]是另一個組合。總共有$ 2^4 $的組合,所以我使用了幾個嵌套循環來生成這個數組列表。但是,當我嘗試運行循環時,出現「內存不足」錯誤。看看:嵌套循環導致OutOfMemory錯誤:Java堆空間

String[] t4 = new String[4]; 

ArrayList<String[]> list4 = new ArrayList<String[]>(); 

for(int i=0; i<= 1; i++) 
{ 
String count = Integer.toString(i);  
t4[0]=count; 
list4.add(t4); 
for(int j=0; j<= 1; j++) 
{ 
String count1 = Integer.toString(j);  
t4[1]=count1; 
list4.add(t4); 
    for(int k=0; k<= 1; k++) 
    { 
    String count2 = Integer.toString(k);  
    t4[2]=count2; 
    list4.add(t4); 
    for(int m=0; m<= 1;) 
    { 
    String count3 = Integer.toString(m);  
    t4[3]=count3; 
    list4.add(t4); 
    t4 = new String[4]; 
    } 
    } 
} 
} 

我的循環有什麼問題嗎?或者有另一種方法來生成所需的數組列表?

+1

你忘了在你的'm''中增加'm' for'循環。這是一個無限循環。 – rgettman

回答

8

您有:

for(int m=0; m<= 1;) 

您需要:

for(int m=0; m<= 1; ++ m) 

否則,它是一個無限循環,最終結束了String[4]的填補list4直到你耗盡內存。

通過不遞增mm保持爲0並且循環條件始終爲真。

+0

好,趕快。 – hexafraction

2

您不要修改m

更改此

for(int m=0; m<= 1;) 

for(int m=0; m<= 1;m++) 
0

在你內心的 'for' 循環,你忘了遞增變量 'M',因此它正在進入無限循環。

0

問題是沒有m ++。此外,循環應該看起來像這樣:

for(int i=0; i<= 1; i++) 
{ 
String count = Integer.toString(i);  
for(int j=0; j<= 1; j++) 
{ 
String count1 = Integer.toString(j);  
    for(int k=0; k<= 1; k++) 
    { 
    String count2 = Integer.toString(k);  
    for(int m=0; m<= 1;m++) 
    { 
    String count3 = Integer.toString(m);  
    t4[0]=count; 
    t4[1]=count1; 
    t4[2]=count2;  
    t4[3]=count3; 
    list4.add(t4); 
    t4 = new String[4]; 
    } 
    } 
} 
}