I have the following code:
public class Main { static void swap (Integer x, Integer y) { Integer t = x; x = y; y = t; } public static void main(String[] args) { Integer a = 1; Integer b = 2; swap(a, b); System.out.println("a=" + a + " b=" + b); } }
I expect it to print a=2 b=1, but it prints the opposite. So obviously the swap method doesn't swap a and b values. Why?
The reason it didn't swap is because primitive variables are passed by value. This is what happens: Arguments are evaluated to values. Boxes for parameter variables are created.
You need to pass the memory address reference of the values so that the operation is done on the memory address of the original values. Swap needs to accept the memory reference of the values and store them in pointers which will perform operations to the original values' memory location.
The swap() method of java. util. Collections class is used to swap the elements at the specified positions in the specified list. If the specified positions are equal, invoking this method leaves the list unchanged.
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.
This doesn't have anything to do with immutability of integers; it has to do with the fact that Java is Pass-by-Value, Dammit! (Not annoyed, just the title of the article :p )
To sum up: You can't really make a swap method in Java. You just have to do the swap yourself, wherever you need it; which is just three lines of code anyways, so shouldn't be that much of a problem :)
Thing tmp = a; a = b; b = tmp;
Everything in Java is passed by value and the values of variables are always primitives or references to object.
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