Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

enhanced for

 
venkatesh badrinathan
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why cant we use enhanced for loop for two dimensional variables??? please explain
 
venkatesh badrinathan
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops.. am sorry, i meant,

why cant i get the output for this program where i have used two dimen array,
my output was,
[I@3e25a5
[I@19821f
(which made me think that i cant use 2d here..)
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The issue isn't so much with the enhanced for loop; its the System.out.println() call with an array as the parameter. This is resulting in an implicit call to the toString() method on an array. As such, you do not get the contents of the array output. Even if you do this outside of a for loop, you'd get something similar. For example, the code:


would output something like:
[I@9304b1


To print out the contents of the array, we need to use a utility method in the java.util.Arrays class (notice the plural Arrays). In particular, we can use one of the overloaded toString() methods:



This would result in the output:
[1, 2, 3]


So you can change your code to

And that will output the each of the arrays. So you'd get:

[5, 3, 2]
[4, 3, 2]


And if you want to iterate through the "sub-array" you can out a seconffor loop inside the first for loop:

This would output:

5
3
2
4
3
2

Does that help?
[ August 15, 2008: Message edited by: Mark Vedder ]
 
venkatesh badrinathan
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yeah.. really it does.
Thank Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic