Reputation: 1248
I want to create a 2D array [3][3] ; each element should be a 3x3 character array How can I accomplish this in java?
Upvotes: 0
Views: 249
Reputation: 236170
That seems complicated … but still, this is how:
char[][][][] board = new char[3][3][3][3];
This sounds like a Sudoku board. It'd be much, much easier if you defined a 9x9 2D char
array, taking care of iterating over the right zones whenever you have to (simply by controlling the looping variables). Trust me, thinking in terms of a 4D array is gonna be a headache.
Upvotes: 2
Reputation: 2920
This could also work:
Object[][] array = new Object[3][3];
char[][] subArray = new char[][] {{'a','b','c'},
{'d','e','f'},
{'g','h','i'}};
array[0][0] = subArray;
// initialize remaining arrays here
Upvotes: 0
Reputation: 2607
Create Array Class:
public class 2DChar {
private char[][] elem = new char[3][3];
//getters, setters...
}
Create Array of Array elements:
2DChar[][] 2dCharArray = new 2DChar[3][3];
Initialise it:
for(int i = 0; i < 2dCharArray.lenght(); i++) {
for(int j = 0; j < 2dCharArray[i].lenght(); j++) {
2dCharArray[i][j] = new 2DChar();
//set value, etc...
}
}
Upvotes: 1