• Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating and using Arrays  RSS feed

 
Urs Waefler
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the code:
In this code I do not understand the for statement. How does it work?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have a 2D array. So the for loop gets each "inner" array and operates on it.

Make sense? If not, what's a more specific question you are puzzled about?
 
Urs Waefler
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand that it is a two dimensional array. I can make a picture of it; that is fine. But what I do not understand is the for statment. How does it work when we have for instance a 3D array? Does the for statement operate on the most "inner" array?
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What does not make sense to people (well, at least to me) is how you can say "I understand it is a two-dimensional array. I can make a picture of it" but then turn around and say you don't understand the for-loop.  If you understand the structure of the array, then understanding what the for-loop is doing should be straightforward.

The array you declared is an array of arrays:

The for-loop is simply iterating over the elements of table, which are table[0], table[1], and table[2]. Each element happens to be a String[], which is why the for-loop variable is declared as such. Since each element is itself an array, then you can reference its length attribute and print it out. Your output would be the number of elements of each nested array.

There is no relationship between what a for-loop does and how deeply nested an array is. It's up to you to give the for-loop an Iterable (arrays are Iterable) so that it can iterate and do something with each element in that Iterable. The for-loop doesn't care what the element is. In this case, it just happens to be an array.  If you have a more deeply-nested array, such as a String[][][], then YOU have to figure out what to do with each element and write code accordingly.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!