1

I want to initialize a 2d array in java which can hold different data types like char, int etc. My 2d array would be something like this -

  1 2 3 4 5 6 7
1 S S S S S S S
2 S S S S S S S
3 S S S S S S S
4 S S S S B S S
5 S S S S S S S
6 S S S S S B S
7 S S S S S S S

There is a space before 1 and I want to include that in my array.If I can initialize that, how can I do that? Do I use ASCII convention while inputting the string values or something? Please help. Note - I don't want to print the matrix, I will input these values manually.

3
  • 1
    An array can only hold one type of data. You could do a work around by using an Object array with the wrapper classes, or an int array where you know exactly which indices can be downcast to a char. Commented Feb 7, 2021 at 11:05
  • It is very likely that you need to use char 2D array here. Of course, using 2D array of raw objects is possible, but in this case you cannot be sure which type is stored in each cell of the array. Commented Feb 7, 2021 at 11:10
  • Please keep in mind that it's a very bad idea to switch to an non-typed data structure. What's mode, in your case numbers are just the "coordinates", which can be easily computed from the array index... Commented Feb 7, 2021 at 11:12

1 Answer 1

1

I see two solutions if you want to use a single primitive type in the array, either treat the numbers as characters so you can have an array of char

char[][] array2d = new char[8][8]

or simply ignore the numbers and only include the characters and deduct the right number from the index (x,y) in the array

char[][] array2d = new char[7][7]

so for array2d[3][5] the numbers would be 4 and 6

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.