2

Using java, is there a way to set certain values in an array to be static/uneditable? I'm trying to make a sudoku game, so I want the initial numbers to be set so the program can't change them, but the other numbers to be changeable. I've done some googling so far but none of my searches have brought up any relevant information.

4
  • This comes more down to your class design. Just protect the data with accessor methods. Commented Feb 25, 2013 at 19:19
  • 1
    It is not possible with arrays, but you can design your own class and make sure that certain fields cannot be edited. Commented Feb 25, 2013 at 19:21
  • There is no way to mark any or all of the elements of an array as "read only". The best you can do is "hide" the array behind a method call. You can use final on the reference to the array, but that will just make it (sort of) impossible to change which array is referenced -- it will not prevent modification of the array. Commented Feb 25, 2013 at 19:22
  • Create 2 2D arrays, one a clone of the other and just set one to static and the other to final. Then you can fill in 1 array to have it fill with -1's instead of 0's and use that to do a modifiable check. Or, you can have 1 2D array of int's and have 1 of booleans. Initial numbers would be 'false' in the isEditable boolean table then if they are linked together correctly. Commented Feb 25, 2013 at 19:32

1 Answer 1

2

You have to hide the array by making it private. And never return the reference to the array instead return a clone.

e.g.

public class ArrayHolder {
    private String[] array;

    public ArrayHolder(String[] inputArray) {
        //make a copy of inputArray
        //assign the reference to the copy to this.array
    }

    public String[] getArray() {
        //make a copy of the array
        //return the reference to the copy
    }
}

As far as making some elements updatable, you have to write mutator method(s) in the class, so that only those methods can change certain elements in the array.

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.