0

The way I have been trying works up until 03 and then skips the element. Now I understand that the array I am creating is a 3x3 so to say. I just do not understand how to create different lines of different lengths. Any help would be appreciated!

String[][] copied = new String[test._data.length][test._data[0].length];
    for(int i = 0; i < test._data.length; i++ ) {
        for(int y = 0; y < test._data[0].length ; y++)
        {
            copied[i][y] = test._data[i][y];
        }
    }


String[][] _data = {
              {"A", "B"},
              {"01", "02", "03"},
              {"XX"}};
oofer
  • 1
  • 1

2 Answers2

2

It's because the array you are working with is not "square" (the different inner arrays are not of the same size). You are treating the "copied" String array as a square multidimensional array with the second dimension having a length of the first element in the original array. However, the second element in your original array is longer than this length so therefore it will not "fit" inside your blank array.

Try using Arrays.copyOf();

import java.util.Arrays;
class Main {
  public static void main(String[] args) {
    String[][] _data = {
              {"A", "B"},
              {"01", "02", "03"},
              {"XX"}};

    String[][] copied = new String[_data.length][];
    for(int i = 0; i < _data.length; i++) {
      copied[i] = Arrays.copyOf(_data[i], _data[i].length);
    }

    System.out.println(Arrays.deepToString(copied));
  }
}
Jaeheon Shim
  • 491
  • 5
  • 14
0

So your problem is how to instantiate a 2 d arrays with different number of columns As mentionned in the second answer The idea is to create the rows, and after that use a loop for filling the number of column Fro example if you want to create the table copied from the table _data you can use the following :

String[][] copied = new String[test._data.length][];
for(int i = 0; i < test._data.length; i++ ) {
 //for each row , we create manually a string array with the customized length   
copied[i]=new String[test._data[i].length]; 
//create a String table with size as the ith row in the table _data
for(int y = 0; y < test._data[i].length ; y++)
    {
        copied[i][y] = test._data[i][y];
    }
}
NASSIM ADRAO
  • 145
  • 1
  • 9