Possible Duplicate:
Is it possible to write swap method in Java?
Given two values x and y, I want to pass them into another function, swap their value and view the result. Is this possible in Java?
Two variables can be swapped in one line in Java. This is done by using the given statement. x = x ^ y ^ (y = x); where x and y are the 2 variables.
Given two variables, x, and y, swap two variables without using a third variable. The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum.
The Java Collections Framework's classes have a built-in method to swap elements called swap(). The java. util is a utility class that contains static methods that can operate on elements like Lists from the Collection interface. Using the swap method is much easier than the example we discussed earlier.
Not with primitive types (int
, long
, char
, etc). Java passes stuff by value, which means the variable your function gets passed is a copy of the original, and any changes you make to the copy won't affect the original.
void swap(int a, int b) { int temp = a; a = b; b = temp; // a and b are copies of the original values. // The changes we made here won't be visible to the caller. }
Now, objects are a bit different, in that the "value" of an object variable is actually a reference to an object -- and copying the reference makes it point at the exact same object.
class IntHolder { public int value = 0; } void swap(IntHolder a, IntHolder b) { // Although a and b are copies, they are copies *of a reference*. // That means they point at the same object as in the caller, // and changes made to the object will be visible in both places. int temp = a.value; a.value = b.value; b.value = temp; }
Limitation being, you still can't modify the values of a
or b
themselves (that is, you can't point them at different objects) in any way that the caller can see. But you can swap the contents of the objects they refer to.
BTW, the above is rather hideous from an OOP perspective. It's just an example. Don't do it.
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