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.

6
  • 1
    Is this int[][] field static, by the way? If yes, then that's the root of your problems. Commented Apr 16, 2014 at 13:56
  • 3
    Could you provide the relevant code for your class definition? Commented Apr 16, 2014 at 13:57
  • 1
    Look here : stackoverflow.com/questions/413898/… Commented Apr 16, 2014 at 13:57
  • Could you post a little bit of code and as @LuiggiMendoza said if it is static that is the problem Commented Apr 16, 2014 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. Commented Apr 16, 2014 at 14:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.