3

So I have a function that needs to get a 2d Array of Character (the object).

I want to insert it's values from a 2d char array, and it works, but when I try to send the array to the function, it fails to read it as a Character 2d array, and returns null.

This is the code:

char[][] arr = board.getBoard();
                    Character[][] c = new Character[board.getX()][board.getY()];
                    for(int i=0; i<board.getX(); i++) {
                        for(int j=0;j<board.getY();j++) {
                            c[i][j] = (char)arr[i][j];
                        }
                    }

the casting for arr into char doesn't work well when I'm sending c later to the function.

The interesting thing happens when I decide to hard insert the values into c, like this:

Character[][] c = new Character[5][4];
                    c[0][0] = 's';
                    c[0][1] = '|';
                    c[0][2] = '7';
                    c[0][3] = ' ';
                    c[1][0] = ' ';
                    c[1][1] = '|';
                    c[1][2] = 'L';
                    c[1][3] = 'r';
                    c[2][0] = '-';
                    c[2][1] = 'J';
                    c[2][2] = ' ';
                    c[2][3] = '|';
                    c[3][0] = '7';
                    c[3][1] = 'J';
                    c[3][2] = '-';
                    c[3][3] = 'J';
                    c[4][0] = ' ';
                    c[4][1] = 'g';
                    c[4][2] = ' ';
                    c[4][3] = '-';

When I do this, the code works well and the function is able to work with c.

I need some sort of solution, like casting, but I prefer a better solution if you have one.

Cheers!

Dor Sivan
  • 29
  • 3

2 Answers2

0

I have not found the 'correct' way to do this, but I have found a way to this.

I had to do it the other way around:

//create Character array
Character[] characters = new Character[]{'a', 'b', 'c', 'd'};

//create char array
char[] letters = new char[characters.length];

//loop through array
for (int i = 0; i < letters.length; i++){
    //assign value to char
    letters[i] = characters[i].charValue();
}

To do this the other way around wasn't to difficult either:

//create char array
char[] characters = new char[]{'a', 'b', 'c', 'd'};

//create Character array
Character[] letters = new Character[][characters.length];

//loop thorugh char array
for (int i = 0; i < letters.length; i++){
    //assign value to Character
    letters[i] = characters[i];
}

doing this with a 2d array shouldn't be that hard

arrayZero
  • 352
  • 1
  • 3
  • 8
0

it is not possible to cast a char[] to a Character[]
so neither char[][] to a Character[][]
so that's how

char[][] chars = {…};
Character[][] characters = new Character[chars.length][0];
Arrays.setAll( characters, i -> {
  Character[] row = new Character[chars[i].length];
  Arrays.setAll( row, j -> chars[i][j] );
  return( row );
} );
Kaplan
  • 2,572
  • 13
  • 14