Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

arrays in java

Name: Anonymous 2007-01-16 10:27

can someone tell me how to copy a 2 dimensional array to a 1 dimensional one? Ie.
array:
{2, 3, 5}
{4, 7, 9}
should become {2, 3, 5, 4, 7, 9}

Name: Anonymous 2007-01-16 11:06

Here is a method I wrote in a few minutes. There is probably an easier way. This should work for any 2D array of integers or you can change int so that it will work with whatever type of 2D array you want.

public static int[] convertArray( int[][] oldArray )
{
    int numElements = 0;

    // Finds total number of elements of 2D array
    for( int a = 0; a < oldArray.length; a++ )
    {
        for( int b = 0; b < oldArray[ a ].length; b++ )
        {
            numElements++;
        }
    }

    // Creates a new 1D array
    int[] newArray = new int[ numElements ];

    int currentIndex = 0;

    // Writes values of 2D array into 1D array
    for( int a = 0; a < oldArray.length; a++ )
    {
        for( int b = 0; b < oldArray[ a ].length; b++ )
        {
            newArray[ currentIndex ] = oldArray[ a ][ b ];
            currentIndex++;
        }
    }

    return newArray;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List