Reputation: 49
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.
Upvotes: 0
Views: 71
Reputation: 20618
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.
Upvotes: 3