I was working in a problem and I found that Java references are not working as I expect it to. Ofcourse, I am the culprit :), can someone please me why the following happens. Let me first post the code here.
package misc.matrix;
public class ReferenceTester {
public static void main(String args[]){
Boolean[][] input = {
{true ,false ,true ,true ,false },
{false ,true ,true ,true ,true },
{true ,true ,true ,true ,true },
{true ,true ,true ,true ,true },
{true ,false ,true ,true ,true }
};
print(input);
for(Boolean[] eachRow:input){
for(Boolean eachVal:eachRow){
eachVal = Boolean.TRUE;
}
}
print(input);
/*Expected output
true true true true true
true true true true true
true true true true true
true true true true true
true true true true true
*/
}
/**
* Simply prints the array
*/
private static void print(Boolean[][] input) {
for(Boolean[] outArray:input){
for(Boolean iVal:outArray){
System.out.print(iVal?iVal+" ":iVal+" ");
}
System.out.println();
}
}
}
If you take a look at the above program, all I am trying to do is to change all the values in the Array to true and print it. But its simply prints the input again.
Can someone please tell me why is this. Initially I had used the primitive boolean in the program, but since I dont want to create copies, I used the wrapper Boolean Class which is a Java OBJECT as opposed to primitives. (Isnt eachVal a JAVA OBJECT!?!?!?!?)
Why is this happening in Java. Why did it not print all the values to be true?
Please advise.
You cannot modify the source object within a foreach loop. Your loop will have to be a standard for loop like this:
Edit: To be more precise,
eachValin your loop is a pointer, not a reference; hence setting it to point to a different value does not change the original.The exact form that the foreach loop uses behind the scenes is given here, if you wish to confirm this independently.