简体   繁体   中英

Nested loop leads to OutOfMemory Error: Java heap space

I'm trying to create an array list of string arrays containing all possible combinations of 0s and 1s, in four dimensions. That is, [0,0,0,0] is one combination and [0,0,0,1] is another. There are $2^4$ total combinations, so I'm using several nested loops to generate this array list. However, when I try to run the loop, I get an "out of memory" error. Take a look:

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];
   }
  }
 }
}

Is there something wrong with my loop? Or is there another way to generate the desired array list?

You have:

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

You need:

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

Otherwise it's an infinite loop that ultimately ends up filling up list4 with String[4] 's until you run out of memory.

By not incrementing m , m stays at 0 and the loop condition is always true.

You don't modify m

Change this

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

to

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

在内部的“ FOR”循环中,您忘了增加变量“ m”,因此它进入了无限循环。

The problem was with absence of an m++. Also, the loop should look like this:

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];
   }
  }
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM