简体   繁体   中英

how to iterate 2d array java

I have 2d array called myarr[3][3] and I want to to get myarr[0][0] , myarr[0][1] , and myarr[0][2] in another 1d array called arr1[3] . The same for myarr[1][0] , myarr[1][1] , and myarr[1][2] in another 1d array called arr2[3] , and so on.

How can I do something like that in Java?

I have tried to use for loop but I stopped and couldn't know what to write inside it.

for(int i=0 ; i<3 ; i++){
    for(int j=0 ; j<3 ; j++){
        //what can i write here
    }
}

Instead of using an explicit for loop, you could use System.arraycopy() . These are the method signature and description:

arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

Then, to copy the contents from myarr[0] to arr1 you could do:

System.arraycopy(myarr[0], 0, arr1, 0, arr1.length);

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