Bob Johnson
Bob Johnson

Reputation: 1

How can I store a string Matrix inside an array?

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

Answers (4)

Heisenbug
Heisenbug

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

Habib Zare
Habib Zare

Reputation: 1204

use something like this:

String [][] strArr = new String[3][20];
ArrayList<String[][]> tm = new ArrayList<String[][]>();
tm.add(strArr);

Upvotes: 0

swemon
swemon

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

EyalAr
EyalAr

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

Related Questions