简体   繁体   中英

multidimensional array row to single array java

Hi I have the array below, I need to copy the contents into another single dimensional array but only the first row eg 0 and 1

String data[][] = new String[][]
   {
      {"0", "1", "2", "3", "4"},
      {"1", "1", "2", "3", "4"}
   }

The above code is an example of how I have set my array, I just need the first row but for every colum

I have tried:

for (int r = 0; r < data.length; r++)
   {
    codes = new String[]  {data[r][0]};
   }

But that doesnt work, any ideas? Thanks

Try this:

String[] codes = new String[data.length];
for (int r = 0; r < data.length; r++) {
    codes[r] = data[r][0];
}

That should work

Or try:

String[] codes = new String[data.length];
int i=0;
for(String[] strings : data)
{
    codes[i++]=strings[0];
}

Although honestly, since foreach code creates a counter, you may be better off using the type of loop that goatlinks showed.

The data contained in data[r][0] is a String. Not a String[] (Array of Strings).
What you want to do: create an array that has the same size as you have columns. String[] codes = new String[data.lenght] and then assign the [r][0] element of data to the r-th element of your newly created array: codes[r] = data[r][0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM