[英]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. 我必须在length
可能会变化的array
存储String
矩阵(3x20) 。 I am trying the following code but I am getting an incompatible types
error. 我正在尝试以下代码,但出现了incompatible types
错误。
How could I fix this error? 我该如何解决该错误?
My code is: 我的代码是:
int x=0;
String[] arrayF=new String[10];
arrayF[x]= new String[3][20];
You can't assign array this way. 您不能以这种方式分配数组。 You should eventually assign each element of the first 2-array to the 1-d array. 您最终应该将第一个2数组的每个元素分配给1-d数组。
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];
}
}
arrayF
is an array of strings , so each element in arrayF
must be a string (by definition of the array). arrayF
是一个字符串数组 ,因此arrayF
每个元素arrayF
必须是一个字符串(根据数组的定义)。
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). 您想做的是在arrayF
每个元素中放置一个数组( new String[3][20]
),而不是一个字符串,这显然与它的定义相矛盾(因此, incompatible types
错误)。
One solution for what you want might be using a 3-d array of strings: 您想要的一种解决方案可能是使用3-d字符串数组:
String[][][] arr = new String[10][3][20];
arrayF is one dimensional array with String type. arrayF是String类型的一维数组。 You cannot add two dimensional array to arrayF. 您不能将二维数组添加到arrayF。 For dynamic array size, you should use ArrayList. 对于动态数组大小,应使用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 请参阅Java中的可变长度(动态)数组
use something like this: 使用这样的东西:
String [][] strArr = new String[3][20];
ArrayList<String[][]> tm = new ArrayList<String[][]>();
tm.add(strArr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.