Reputation: 15
I am trying to add another column of data to the end of my 2d array, but cannot make it work. Any help would be great. This is what I have so far.
double[] d = a.Total();
String[][] sr = a2.records();
String[] d2 = new String[d.length];
for (int i = 0; i < d.length; i++)
d2[i] = String.valueOf(d[i]); // converts double[] into string[]
My desired result is a 2d array all[sr.length + 1][] with the last column of data being d2. Both arrays have the same amount of rows.
thankyou
Upvotes: 0
Views: 8502
Reputation: 45060
String[][] sr = a2.records();
When you do this, your sr
array is created with a fixed no. of rows and columns returned from the ar.records()
. Arrays are not dynamic in nature, hence, once created, you cannot add additional rows/columns to it. Therefore, you need to create a new array(with higher row/column count) with all the values from sr
array copied to it, and then the new column being added to it.
Another better solution is to use ArrayList, instead of arrays, as they are dynamic(you can add newer elements as and when you want).
Edit: You can do something like to copy your data from old array to new array and add the d
array as the new row
String[][] newsr = Arrays.copyOf(sr, sr.length + 1); // New array with row size of old array + 1
newsr[sr.length] = new String[sr.length]; // Initializing the new row
// Copying data from d array to the newsr array
for (int i = 0; i < sr.length; i++) {
newsr[sr.length][i] = String.valueOf(d[i]);
}
Upvotes: 1
Reputation: 271
It cannot be done using arrays. The only way is to create a new array of size n+1 or more and copy all the values from old one. For example:
String[][] sr2 = Arrays.copyOf(sr,sr.length + 1);
sr2[sr2.length-1]=d2;
Try using Lists (ArrayList or Linked list if you need to add new columns frequently)
Upvotes: 0