0

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

2
  • I want a new 2d array with with the same data as the 2d-array + the extra column of data (d2) Commented Oct 14, 2013 at 10:24
  • Why dont you use ArrayList or Vector? Commented Oct 14, 2013 at 10:33

2 Answers 2

1
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]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I want to create a new 2d array.
0

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)

1 Comment

Yes I want to copy the data of both arrays and merge them in to a new 2d array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.