To simplify things, here is a version of a so-called swap, which does
not swap, but simply assign values to objects.
1 - First version:
class Something {
public String a;
public Something() {}
public Something(String a) {
this.a = a;
}
}
public class Main2 {
public static void main(String[] args) {
Something element_a = new Something("aaa");
Something element_b = new Something("bbb");
swap(element_a, element_b);
System.out.println(element_b.a);
System.out.println(element_a.a);
}
static void swap(Something element_a, Something element_b) {
// element_a = element_b;
element_b.a = "toto";
element_a.a = element_b.a;
}
}
run:
toto
toto
BUILD SUCCESSFUL (total time: 2 seconds)
writing element_b.a="toto" is like writing element_b.setA()="toto". So
you actually work with the object element_b and change the value of
its variable a.
writing element_a.a = element_b.a is like writing element_a.setA() =
element_b.getA() . So you work again with the object element_a and
change the value of its variable a.
Hence you retrieve in Main the same objects with their internal value
changed to "toto".
2 - Second version with element_a = element_b commented out
run:
toto
aaa
BUILD SUCCESSFUL (total time: 2 seconds)
In Java, a variable representing an object is actually a reference to
that object.
So that writing element_a = element_b is like saying make the variable
element_a (which represents the object element_a) points to the same
object as the variable element_b (which represents the object
element_b).
After that, you have the variables element_a and element_b which point
to the same object element_b.
Then element_b.a = "toto" assign the value "toto" to element_b, but
also to element_a as they point to the same object in the scope of
swap function after element_a = element_b.
Then element_a.a = element_b.a does not much as it is as to say
element_b.a = element_b.a, which hopefully is true. (you may check it
by commented it out; you may also commented it out in first version
and you'll see that it is no more neutral, that is it changes the
result of run).
To put it briefly, you have only changed element_b value in swap
function.
Then when you return to Main, you retrieve the value of element_a
unchanged, and the value of element_b changed by the swap method.
I've uploaded a graphic illustrating the differences between the
versions (swapstring.png).
--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/javaprogrammingwithpassion?hl=en
-~----------~----~----~----~------~----~------~--~---