0

I have to store a String matrix(3x20) inside an array whose length may vary. I am trying the following code but I am getting an incompatible types error.

How could I fix this error?

My code is:

int x=0;    
String[] arrayF=new String[10];    
arrayF[x]= new String[3][20];
Alex K
  • 22,315
  • 19
  • 108
  • 236

4 Answers4

1

You can't assign array this way. You should eventually assign each element of the first 2-array to the 1-d array.

Something like:

String[][] array2D =new String[M][N];
String[] array1D = new String[M * N];

for (int i = 0 ; i < M ; i++)
{
    for (int j = 0 ; i < N ; i++)
    {
         array1D[(j * N) + i] = array2D[i][j];
    }

}
Heisenbug
  • 38,762
  • 28
  • 132
  • 190
0

arrayF is an array of strings, so each element in arrayF must be a string (by definition of the array).
What you are trying to do is is put an array (new String[3][20]), instead of a string, in each element of arrayF, which obviously contradicts it's definition (hence the incompatible types error).
One solution for what you want might be using a 3-d array of strings:

String[][][] arr = new String[10][3][20];
EyalAr
  • 3,160
  • 1
  • 22
  • 30
0

arrayF is one dimensional array with String type. You cannot add two dimensional array to arrayF. For dynamic array size, you should use ArrayList.

List<String[][]> main = new ArrayList<String[][]>();

String[][] child1 = new String[3][20];
String[][] child2 = new String[3][20];
main.add(child1);
main.add(child2);

Refer to Variable length (Dynamic) Arrays in Java

Community
  • 1
  • 1
swemon
  • 5,840
  • 4
  • 32
  • 54
0

use something like this:

String [][] strArr = new String[3][20];
ArrayList<String[][]> tm = new ArrayList<String[][]>();
tm.add(strArr);
Habib Zare
  • 1,206
  • 8
  • 17