0

This issue arose when I changed all my variables to be stored into an int[][]. I have an object. Every time I click a button I create a new object which has its own variables. The problem is that I decided to store all the int variables in an int[][] and now every object that I created uses the same int[][] grid. So I'm not sure what I may be doing wrong here.

I have tried initiating the array int[][] within the object constructor and outside the constructor i.e. public static int[][] grid; and then initiate it inside the constructor or I've initiated it within the constructor as int[][] grid = new int[20][20].

Any ideas as to why this is happening? Before I had a specific String variable to hold that int value but when I changed it everything to be stored in a int[][] all the new objects I create use the same grid.

durron597
  • 31,968
  • 17
  • 99
  • 158
Iron
  • 49
  • 9
  • 1
    Is this `int[][]` field `static`, by the way? If yes, then that's the root of your problems. – Luiggi Mendoza Apr 16 '14 at 13:56
  • 3
    Could you provide the relevant code for your class definition? – ajp15243 Apr 16 '14 at 13:57
  • 1
    Look here : http://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class – UserFuser Apr 16 '14 at 13:57
  • Could you post a little bit of code and as @LuiggiMendoza said if it is static that is the problem – 3kings Apr 16 '14 at 13:58
  • Yes my fields are static. Also, i can't post the code on here I tried before but it says I'm not doing it correctly so I gave up on that. I will try and remove the static insertion and get back to you guys. Thank you. – Iron Apr 16 '14 at 14:01
  • Can I see the code where the exact problem is taking place. I want to recreate the problem. – CodeCamper Apr 16 '14 at 14:04

1 Answers1

3

Providing us your code would have been wonderful. Helping is so much easier when having the code you are talking about. But there was a little word in your explanation that caught my attention: static.

I have tried initiating the array int[][] within the object constructor and outside the constructor ie. public static int[][] grid; and then initiate it inside the constructor or I've initiated it within the constructor as int[][] grid = new int[20][20].

You wrote: public static int[][] grid

This means you made your field static. Static fields belong to the class, but not to an instance. So all your instances share the same grid. Even if you instantiate it new in the conctructor, there will be only one such grid.

If you want a design, where each instance has its own grid, simply delete the static keyword.

Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66