1

I am using a function that returns some integers

int[] return;

This function is inside a loop like this

public static int[] toEOBArray(double[] tempVal) 
{
    int[] out;
    for (int i = 0; i < 10; i++)
    {
        out = fixArray(tempVal[i]);
    }
    return out;
}

What I want is as new arrays come from fixArray to add them to the previous results, so in the end I have a big array that will contain all the small arrays resulting from fixArray

What is the most efficient way of doing this? My main problem is not knowing how to initialize the array that is to hold all the values.

ealiaj
  • 1,525
  • 1
  • 15
  • 25

2 Answers2

4

If you want to work only with arrays, you must first find the length of the concatenated array. Then you can use System.arraycopy to copy the small arrays to the output array.

public static int[] toEOBArray(double[] in) 
{
    int[][] arrays = new int[10][];
    int len = 0;
    for (int i = 0; i < 10; i++)
    {
        arrays[i] = fixArray(tempVal[i]);
        len += arrays[i].length;
    }
    int[] out = new int[len];
    int offset = 0;
    for (int i = 0; i < 10; i++)
    {
        System.arraycopy(arrays[i],0,out,offset,arrays[i].length);
        offset += arrays[i].length;
    }
    return out;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • And that effort only because some programmer still like to use arrays... But ok, it's their choice. – Tom May 31 '15 at 08:25
  • 2
    @Tom I agree that using only arrays involves more code, and I would probably prefer to use a Collection to aggregate the arrays, but using arrays also has performance benefits (at least finding the required length of the output array in advance does - if you know the final length, you can initialize an ArrayList with that capacity and have similar performance). – Eran May 31 '15 at 08:29
  • @Eran I am working on this using Eclipse and I get a `The variable arrays can only be null at this location` warning. Does that have any significance? – ealiaj May 31 '15 at 08:39
  • 1
    @green_leaf my bad, see edit – Eran May 31 '15 at 08:40
0

If you insist on working with native arrays (as opposed to a Collection like ArrayList) then you will want to use ArrayUtils class from Apache Common Lang that adds many Collection-like features to Java native arrays, one of which is addAll:

ArrayUtils.addAll(fixArray, tempVal);
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47