简体   繁体   English

在Java中遍历二维数组

[英]traversing a 2-dimensional array in java

i watch in a tutorial that i can traverse an array of object in this way: 我在一个教程中看到,我可以通过这种方式遍历对象数组:

     Animals[] an = new Animals[2];

         for (Animals a:an){
                 .
                 .
         }

But now i want to traverse a 2 dimensional array and when i use this code i have a problem(says:incompatible types required:appl1.Animals foundLappl1.Animals[]). 但是现在我想遍历二维数组,当我使用此代码时,我遇到了一个问题(说:不兼容的类型必需:appl1.Animals foundLappl1.Animals [])。 when i use this code 当我使用此代码

   Animals[][] an = new Animals[2][2];

      for (Animals a:an){
             .
             .
       }

Does anyone knows how can i overcome this problems. 有谁知道我该如何克服这个问题。 Thank you in advance for your help. 预先感谢您的帮助。

You will need to use nested loops, as follows: 您将需要使用嵌套循环,如下所示:

Animals[][] an = new Animals[2][2];

for (Animals[] inner : an) {
    for (Animals a : inner) {
        // Execute code on "Animals" object a
    }
}

Why does this work? 为什么这样做?

Look at your first example (reposted here for convenience): 查看您的第一个示例(为方便起见,在此重新发布):

Animals[] an = new Animals[2];

for (Animals a : an) {
    // Do stuff here.
}

This works because an is an array of Animals objects. 这是有效的,因为anAnimals对象的数组。 The for loop iterates through each Animals object, performing some action on them one-by-one. for循环遍历每个Animals对象,对它们进行一对一的操作。

Now look at my answer posted above (again, reposted here for context): 现在看一下我上面发布的答案(再次在此处重新发布以了解上下文):

Animals[][] an = new Animals[2][2];

for (Animals[] inner : an) {
    for (Animals a : inner) {
        // Execute code on "Animals" object a
    }
}

This works because an is an array of Animals[] objects. 这是有效的,因为anAnimals[]对象的数组。 The first for loop iterates through each Animals[] . 第一个for循环遍历每个Animals[] At that point, you have an array of Animals objects, so you can use the same solution as above: a single for loop to iterate through each of the Animals object and perform some action on them one-by-one. 届时,您将拥有一组Animals对象,因此您可以使用与上述相同的解决方案:一个for循环遍历每个Animals对象并对其进行一些操作。

A two-dimensional array is really an array of arrays. 二维数组实际上是数组的数组。 You need nested loops: the outer loop goes through the array of arrays, and the inner loop goes through the elements of each individual array. 您需要嵌套循环:外部循环遍历数组数组,内部循环遍历每个单独数组的元素。

Animals[][] ann = new Animals[2][2];

for (Animals[] an:ann){
    for (Animals a:an){
         .
         .
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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