Reputation: 1
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];
Upvotes: 0
Views: 1789
Reputation: 39164
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];
}
}
Upvotes: 1
Reputation: 1204
use something like this:
String [][] strArr = new String[3][20];
ArrayList<String[][]> tm = new ArrayList<String[][]>();
tm.add(strArr);
Upvotes: 0
Reputation: 5946
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
Upvotes: 0
Reputation: 3170
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];
Upvotes: 0