0

How do I set up an 2d array (array of arrays in java)?

    dmap = new sq[255][255];
    for (int y = 0; y < 255; ++y)
        for (int x = 0; x < 255; ++x)
            dmap[x][y] = new sq();

where sq is my other class doesn't work well- I get a long hang (2 mins) and no logging or printfs appear in Eclipse debug views (console + log).

John
  • 6,433
  • 7
  • 47
  • 82
  • 3
    Unless `new sq()` hangs, there's no problem in your code. – Sergey Kalinichenko Jul 01 '12 at 03:15
  • 1
    The only possible issue is that this should be `[y][x]` instead of `[x][y]` in the inner loop. See http://stackoverflow.com/questions/9936132/why-does-the-order-of-the-loops-affect-performance-when-iterating-over-a-2d-arra. –  Jul 01 '12 at 03:48

1 Answers1

1

At first You must initialize first dimension of array and then go to next, here is the right code:

sq dmap[][] = new sq[256][];
for (int x = 0; x < 255; ++x){
   dmap[x] = new sq[256];
   for(int y = 0 ; y < 255 ; ++y){
      dmap[x][y] = new sq();
   }
}
Shahryar
  • 1,454
  • 2
  • 15
  • 32