0

So I have a 2-dimensional array in Java where each cell in the array is a Chunk the Chunks hold information about their location. The problem is that in my for loop what seems to be happening is that every time I create a new Chunk I'm just overwriting the information about all the previous chunks

here's my code

public static int worldsize = 5;

public static Chunk[][] chunks = new Chunk[worldsize][worldsize];

public CreateWorld(){
    for(int i = 0; i < worldsize; i++){
        for(int j = 0; j < worldsize; j++)
        {
            System.out.println("creating chunks at postion " + i + ", " + j);
            chunks[i][j] = new Chunk(i, j);
            System.out.println("chunk at positon 0, 0 : " + chunks[0][0].chunkXPos + ", " + chunks[0][0].chunkYPos);
        }
    }

}

and here is the Chunk

public static int chunkXPos;
public static int chunkYPos;

public Chunk(int chunkX, int chunkY){
    chunkXPos = chunkX;
    chunkYPos = chunkY;
    System.out.println(chunkXPos + ", " + chunkYPos);
    cells = createChunkList().clone();
}

The expected output would be this:

creating chunks at postion 3, 2
3, 2
chunk at positon 0, 0 : 0, 0
creating chunks at postion 3, 3
3, 3
chunk at positon 0, 0 : 0, 0

what I actually get

creating chunks at postion 3, 2
3, 2
chunk at positon 0, 0 : 3, 2
creating chunks at postion 3, 3
3, 3
chunk at positon 0, 0 : 3, 2

from what I was able to figure out every time I call = new Chunk(i, j); it sets all the information about all the other chunks as the new coordinates so that's why the chunk at position [0][0] thinks it's at [3][2]

The solution is probably very simple, Although I'm new to java and I can't figure it out

NotAFlyingGoose
  • 111
  • 1
  • 10
  • It's the `static` keyword that's the culprit. `chunkXPos` and `chunkYPos` are basically shared by all instances of `Chunk`. Please see [What does the `static` keyword do in a class?](https://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class/413904). – user Jun 27 '20 at 23:42

1 Answers1

2

I think its because of your Chunk class. What you need to do is set the x and y attributes in the class to be non static.

So try private int chunkYPos; and private int chunkXPos;

Static variables are shared across all instances of that object in Java. You want this to be a variable unique to each chunk (at least from what I understand of your question).

duldi
  • 180
  • 1
  • 17
  • Thats cool, a static variable in a class is useful for things such as tracking how many instances of that object have been created. So you increment once each time the constructor is called. - Theres a little bit more information for you :) – duldi Jun 27 '20 at 23:49