• Post Reply Bookmark Topic Watch Topic
  • New Topic

enhanced for loop  RSS feed

 
Amit Sethi
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Pg325 {
public static void main(String[] args ) {

int[][] twoD = { {1,2,3} , {4,5,6} , {7,8,9} };

for(int x:twoD[2]); // how can a simple variable contain a reference compiling prefectly WHY ?)

for(int[] x : twoD[2]); //incompatible types WHY ? here x is a refrence to an array & twoD[2] contains a refrence:
}
}



pls explain me why compiler is behaving abnormally, what is the logic behind it ?

Regards
Amit Sethi
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My guess would be autoboxing. Autoboxing doesn't work for primitive arrays.
 
Jeroen T Wenting
Ranch Hand
Posts: 1847
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nope. The first works well because you're iterating over an int array which yields ints (or Integers if you use autoboxing).
The second fails for the same reason. While iterating over an int array you're not going to get an int array out of it.
 
Kentaro Shinbashi
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeroen,




Would this compile if it was:



Meaning that x would get each array in the top level array?

Thanks.

Kentaro
 
Amit Sethi
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot guys, now it is clear.

But can you pls help me in my IInd post(Working with sounds in java).

Regards.
Amit Sethi.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Kentaro Shinbashi:

Would this compile if it was:


Yes, exactly.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!