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

16,478

Solution 1

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.

Solution 2

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);

?

Share:
16,478

Related videos on Youtube

Giga Tocka
Author by

Giga Tocka

Updated on September 26, 2022

Comments

  • Giga Tocka
    Giga Tocka over 1 year

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

    • reprogrammer
      reprogrammer
      You should allocate enough rows in your 2D arrays. The way you initialize your 2D array, it cannot have more than 2 rows.
  • Giga Tocka
    Giga Tocka over 11 years
    I'm just learning how to use JTables. From what I've learned I think I'm supposed to initialize JTables with a 1d array for columns and a 2d array for the data. I have no idea what TableModel.addRow(dataArray); does but I will look into it!
  • Giga Tocka
    Giga Tocka over 11 years
    Well, what I'm trying to do is have a panel in which a user enters data. When a button is pressed, the data gets added to the table.
  • Reimeus
    Reimeus over 11 years
    You just need to split out your Strings into a format where you can build an object array so that you can use for your addRow call. Have a look at an example. This may require a new post.
  • Giga Tocka
    Giga Tocka over 11 years
    Thanks a lot, this helped a lot.