java 如何将一维数组添加到二维数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13851009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a 1D array to a 2D array?
提问by Giga Tocka
Sorry first time asking a question here.
抱歉第一次在这里提问。
If I have a 2D Array like this:
如果我有这样的二维数组:
int[][] array2d = {{1, 2, 3}, {6, 7, 8}};
How do I add multiple 1D Arrays like this:
如何像这样添加多个一维数组:
int[] array1d = {3, 2, 1};
int[] array1d2 = {8, 7, 6};
so that my original 2d array becomes this:
这样我原来的二维数组就变成了这样:
int[][] array2d = {{1, 2, 3}, {6, 7, 8}, {3, 2, 1}, {8, 7, 6}};
Note:this is for adding information from a JTextfield into a JTable whenever a button is pressed. So, the 2d array will be used as the data inside the table. If there is a better way to accomplish this I would appreciate it too. =)
注意:这是为了在按下按钮时将 JTextfield 中的信息添加到 JTable 中。因此,二维数组将用作表内的数据。如果有更好的方法来实现这一点,我也将不胜感激。=)
回答by Reimeus
Your array :
你的阵列:
int[][] array2d = {{1, 2, 3}, {6, 7, 8}};
is fixed in size, so you would have to create a copy with enough capacity to hold the new values:
大小是固定的,因此您必须创建一个具有足够容量来保存新值的副本:
int[][] newArray = Arrays.copyOf(array2d, 4);
newArray[2] = array1d;
newArray[3] = array1d2;
To add your data to the JTable
the arrays would have to be first converted to a non-primitive type such as an Integer
array. One option is to use the Apache Commons:
要将您的数据添加到JTable
数组中,必须首先将其转换为非原始类型,例如Integer
数组。一种选择是使用 Apache Commons:
model.addRow(ArrayUtils.toObject(array));
for each row of the array.
对于数组的每一行。
回答by BevynQ
arrays are fixed size so to append it you need to resize the array look at java.util.Arrays.
数组是固定大小的,因此要追加它,您需要调整数组大小,请查看 java.util.Arrays。
then set the arrays location
然后设置阵列位置
arra2d[index] = array1d;
is there are reason you are not using
你有什么理由不使用
TableModel.addRow(dataArray);
?
?