'How to remove an element in a 2D array
I have a 2D array that I need to "reset" each time a tic tac toc game is started. I call a method and loop through the array setting all the elements to Zero. But this defeats the purpose of my program because i need to have all the elements empty/null again.
public static char[][] initializeGame(char[][] gameBoard) {
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
gameBoard = null; //<--THIS IS THE THING AM TRYING TO NULL @ gameBoard[row][column]
}
}
return gameBoard;
}
How can I set the elements of gameBoard to null?
Solution 1:[1]
If you are asking how to change the values of individual elements in a 2D array to null, you would do this:
gameBoard[row][col] = null;
But since you have a 2D char array, you can't do that as char is a primitive type and does not allow having a null value. You could use a different char value to represent empty, or you could make a 2D array have Character objects, but a better solution might be a 2D array of an enumeration type such as:
public enum TicTacToeSquareValue { x, o, empty }
.... later on:
gameBoard[row][col] = TicTacToeSquareValue.empty;
Solution 2:[2]
If you are lazy, you could reinstantiate a new array.
gameBoard = new int[3][3];
I would not recommend this approach, as it is less performant and leaks memory if it is not correctly collected.
A more elegant choice would be to reinitialize the whole array, you dont need to set the values to null since they are of type char
for(int r = 0; r < gameBoard.length; r++)
for(int c = 0; c < gameBoard[r].length; c++)
gameBoard[r][c] = '\0'; //Null character
But hey, why bother writing three lines of code, when there's a prebuilt Java utility method that will help you out?
Arrays.fill(gameBoard, '\0'); //Fills the array with Null characters
Solution 3:[3]
You cannot set a char to null. You can only set it to 0. null is a pointer value, char is a primitive numeric value. Pointers don't fit into primitive values.
So..
gameBoard[row][col]=0
.. should do the trick.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Koray Tugay |
