Reputation: 187
I have a vector of float arrays i.e. Vector . I want to convert this to one float array i.e. move every element in every float[] within the vector to a new float[]. Am a bit puzzled on using the Java built in method vector.toArray() to do this. Any ideas pls?
Upvotes: 1
Views: 1883
Reputation: 383726
There are several ways to do this. You can invoke toArray()
to get several arrays, and then join them into one big array (Guava has utility method to do this). Or you can allocate one big array and then use System.arraycopy
to copy the components array into the appropriate portion of the big array.
Here's an example of the latter:
import java.util.*;
public class Flatten {
static float[] flatten(float[]... arrs) {
int L = 0;
for (float[] arr : arrs) {
L += arr.length;
}
float[] ret = new float[L];
int start = 0;
for (float[] arr : arrs) {
System.arraycopy(arr, 0, ret, start, arr.length);
start += arr.length;
}
return ret;
}
public static void main(String[] args) {
Vector<float[]> v = new Vector<float[]>();
v.add(new float[] { 1,2,3, });
v.add(new float[] { 4, });
v.add(new float[] { });
v.add(new float[] { 5,6, });
float[] flattened = flatten(v.toArray(new float[0][]));
System.out.println(Arrays.toString(flattened));
// prints "[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]"
}
}
With Guava, it looks like you can do this with one line using Floats.concat(float[]...)
:
float[] flattened = Floats.concat(v.toArray(new float[0][]));
It should also be noted that unless you need the thread-safety of Vector
, you should probably use ArrayList
instead.
Upvotes: 1
Reputation: 5845
Vector.toArray() will give you an array of arrays, i.e a two dimensional array. once you have that, you can iterate the array till the length and copy each individual array into one big array.
Works for you?
Upvotes: 1