1

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[]). 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.

2 Answers 2

5

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. The for loop iterates through each Animals object, performing some action on them one-by-one.

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. The first for loop iterates through each 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.

Sign up to request clarification or add additional context in comments.

Comments

4

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){
         .
         .
    }
}

1 Comment

This is correct. You can't do this with a single loop...not without difficulty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.