如何向2D数组中添加1D数组?

时间:2023-02-08 00:24:15

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:

如何添加多个1D数组:

int[] array1d = {3, 2, 1};
int[] array1d2 = {8, 7, 6};

so that my original 2d array becomes this:

我原来的2d数组变成这样

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添加信息。因此,2d数组将用作表中的数据。如果有更好的方法来实现这个目标,我也会很感激。=)

2 个解决方案

#1


5  

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中,数组必须首先转换为非基元类型,例如整数数组。一种选择是使用Apache Commons:

model.addRow(ArrayUtils.toObject(array));

for each row of the array.

对于数组的每一行。

#2


1  

arrays are fixed size so to append it you need to resize the array look at java.util.Arrays.

数组的大小是固定的,所以要添加它,您需要调整数组的大小,看看java.util. array。

then set the arrays location

然后设置数组的位置

arra2d[index] = array1d;

is there are reason you are not using

你不使用的原因是什么

TableModel.addRow(dataArray);

?

吗?

#1


5  

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中,数组必须首先转换为非基元类型,例如整数数组。一种选择是使用Apache Commons:

model.addRow(ArrayUtils.toObject(array));

for each row of the array.

对于数组的每一行。

#2


1  

arrays are fixed size so to append it you need to resize the array look at java.util.Arrays.

数组的大小是固定的,所以要添加它,您需要调整数组的大小,看看java.util. array。

then set the arrays location

然后设置数组的位置

arra2d[index] = array1d;

is there are reason you are not using

你不使用的原因是什么

TableModel.addRow(dataArray);

?

吗?