0

I can't for the life of me figure out what is going on with my code. I know how to set an element in a 2 dimensional arraylist, by doing this :

gridMap.get(0).set(5, 1);

This would set the 6th element in the first inner array to the element 1. (At least this is what it is supposed to do.)

However, when I test the code by running this :

    for (int i = 0; i < gridMap.size(); ++i) {
        for (int y = 0; y < gridMap.size(); ++y) {
            System.out.print(gridMap.get(i).get(y));
        }
        System.out.println();
    }

I get :

0000010000
0000010000
0000010000
0000010000
0000010000
0000010000
0000010000
0000010000
0000010000
0000010000

when it's supposed to be this :

0000010000
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000

What am I doing wrong? I've searched other threads on how to set an element and they all say the code I have above is the way to do it.

John Kim
  • 1,081
  • 10
  • 26
  • Don't think this will solve the problem, but shouldn't it be `y < gridMap.get(i).size()`? Or are you sure it will be square all the time? – vrwim Mar 23 '15 at 00:14
  • @vrwim yes, the grid is square all the time. I'm making a game that uses a 10x10 grid board so I probably should just create a constant called BOARDSIZE. – John Kim Mar 23 '15 at 00:16
  • 2
    I think all rows are references to the same `List` instance. I saw this exact problem yesterday: http://stackoverflow.com/questions/29175195/random-tour-generation-issues – Paul Boddington Mar 23 '15 at 00:18
  • @pbabcdefp Thank you so much! Such a trivial thing, I don't know how I didn't think of it! – John Kim Mar 23 '15 at 00:59
  • @JohnKim Glad I could help. It's so easy to make that mistake. – Paul Boddington Mar 23 '15 at 01:01

0 Answers0