I figured out a a problem in my Code. First the code:
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
String[] blablubb = { "a", "b", "c" };
for(String s : blablubb) {
s = "over";
}
printArray(blablubb);
for (int i = 0; i < blablubb.length; i++) {
blablubb[i] = "over";
}
printArray(blablubb);
}
public static void printArray(String[] arr) {
for( String s : arr ) {
System.out.println(s);
}
}
}
The output is:
a
b
c
over
over
over
I assumed the first loop would also overwrite the String in the array. So the output would be over in any case. It seems it creates a copy of the value instead creating a reference. I never perceived this. Am I doing it wrong? Is there an option to create a reference instead?
//Edit: Seems like everybody knows about that except me. I'm from C background and doesn't pay enough attention to the term reference which is very different to C. Fortunately it took me just 10 minutes to figure this out (this time).
This:
for (String s : blablubb) {
s = "over";
}
Is equal to this:
for (int i = 0; i < blablubb.length; i++) {
String s = blablubb[i];
s = "over";
}
This creates a temporary String with a copy of the value from array and you change only the copy. That's why blablubb[]
content stays untouched.
If you want to change values in the array, just use your second option:
for (int i = 0; i < blablubb.length; i++) {
blablubb[i] = "over";
}
And, by the way, you can print an array with just one line:
System.out.println(Arrays.toString(blablubb));
Your for(String s : blablubb)
loop is equivalent to the following code:
for(int i = 0; i < blablubb.length; i++ ) {
String s = blablubb[i];
s = "over";
}
Hopefully, from this you can see that all you are doing is reassigning a different value to s
without changing blablubb[i]
. This explains the output you see.
The for-each loop don't modify the objects contained in the Collection of objects it's iterating over. It's passing the value not the reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With