tags:

views:

473

answers:

1

Hi everyone I'm in need of help right now. I need to convert 2 dimensional array of numbers to a one dimensional array in Java. Can anyone help me? Have a great day. :)

+1  A: 

Do you mean something like this?

import java.util.*; 

public class Test   
{
    public static void main(String[] args)
    {
        String[][] data = new String[][]
        {
            { "Foo", "Bar" },
            { "A", "B" }
        };

        String[] flattened = flatten(data);

        for (String x : flattened)
        {
            System.out.println(x);
        }
    }

    public static <T> T[] flatten(T[][] source)
    {
        int size = 0;
        for (int i=0; i < source.length; i++)
        {
            size += source[i].length;
        }

        // Use the first subarray to create the new big one
        T[] ret = Arrays.copyOf(source[0], size);
        int index = source[0].length;
        for (int i=1; i < source.length; i++)
        {
            System.arraycopy(source[i], 0, ret, index, source[i].length);
            index += source[i].length;
        }
        return ret;
    }

}

If you want it for primitive types, you'll have to write an overload for each primitive type, but you can use new int[size] instead of Arrays.copyOf at that point.

Jon Skeet
Instead of overloading the method for every primitive, it's easier to write a couple of "boxing" methods which manually boxes the primitives to objects - and still use the flatten method for the flattening :)
Björn
Could you explain exactly what you mean? I can't see how that would really help me turn an int[][] into an int[]. It would also be much less efficient :)
Jon Skeet