Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a 1D array to a 2D array?

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. =)

like image 573
Giga Tocka Avatar asked Oct 25 '25 16:10

Giga Tocka


2 Answers

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:

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

for each row of the array.

like image 90
Reimeus Avatar answered Oct 28 '25 08:10

Reimeus


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

then set the arrays location

arra2d[index] = array1d;

is there are reason you are not using

TableModel.addRow(dataArray);

?

like image 30
BevynQ Avatar answered Oct 28 '25 08:10

BevynQ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!