开发者

Convert from vector of arrays to one array

I have a vector of float arrays i.e. Vector . I want to convert this t开发者_StackOverflowo 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?


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][]));

See also

  • How to flatten 2D array to 1D array?

It should also be noted that unless you need the thread-safety of Vector, you should probably use ArrayList instead.

See also

  • ArrayList vs. Vectors in Java if thread safety isn’t a concern


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜