[英]Can I store a 1d array into a 2d array in java?
I was coding midway when I find out that netbeans give me an error regarding the below code: 当我发现netbeans给出关于以下代码的错误时,我正在中途编码:
String [][]table={getRowArray()};
//getRowArray() will return me a 1D string array
Is there any way to store the 1D array returned by my method into the 2D array directly instead of using a for loop? 有没有办法将我的方法返回的1D数组直接存储到2D数组中,而不是使用for循环? Thanks for any help rendered!
感谢您提供的任何帮助!
For starters - yes, it is possible to do that. 对于初学者 - 是的,有可能做到这一点。
public class Test {
public String[] dum() {
String[] x = {"Not sure"};
return x;
}
public static void main(String[] args) {
Test t = new Test();
String[][] words = {t.dum()};
System.out.println(words[0][0]); // prints "Not sure"
}
}
Double check the error you're getting. 仔细检查你得到的错误。 Make certain that the return type of
getRowArray()
is truly String[]
. 确保
getRowArray()
的返回类型是真正的String[]
。
There may be a better solution for this, but I believe you need to specify a single index for one of the dimensions in order to store it, so you're storing the 1-d Array into a single index of the first-dimension. 可能有更好的解决方案,但我相信您需要为其中一个维度指定单个索引才能存储它,因此您将1维数组存储到第一维的单个索引中。
ie 即
String [][]table;
table[0] = getRowArray();
this should work since the first dimension of the array stores other arrays 这应该工作,因为数组的第一个维度存储其他数组
String [] oneD = { "1", "2", "3", "4" }; // getRowArray();
String [][] twoD1 = { oneD };
String [] anotherOneD = null; // or filled
String [][] twoD2 = { oneD, anotherOneD };
String [][] twoD3 = new String[][] { oneD };
String [][] twoD4 = new String[][] { oneD, anotherOneD };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.