Subtle Development Space
Subtle Development Space

Reputation: 1254

puting 1D arrays into the end of the 2D arrays

Lets say i've got this code:

float[] bigA = {1,2,3,4};
for (int i = 0; i < bigA.length; ++i) {
  float abc = bigA[i] - 1;
  float[] bigerAbc = {abc};
  float[][] wcs = {bigerAbc};
}

The float[][] wcs = {abc}; part is defining the wcs array everytime, and the end result of wcs is {{3}}, but i want wcs to be defined as an empty array, and instead of float[][] wcs = {abc}; i want to write some code to add bigerAbc in the end of the wcs, and in the end wcs should be more like this {{0},{1},{2},{3}}...

To the question is: how can i add a 1D array to the end of a 2D array?

Upvotes: 2

Views: 144

Answers (1)

ykaganovich
ykaganovich

Reputation: 14964

A 2D array in Java is literally an array of arrays, and arrays in java are fixed size. So, you cannot dynamically add an item to the end of an array. You either need to allocate a fixed size array, or use a more flexible structure like a List.

In your example, since the eventual size of wcs is known, you can do the following:

float[] bigA = {1,2,3,4};
float[][] wcs = new float[bigA.length][];
for(int i = 0; i < bigA.length;  ++i) {
  float abc = bigA[i] - 1;
  float[] bigerAbc = {abc};
  wcs[i] = bigerAbc;
}

Upvotes: 5

Related Questions