Tell me please. How to make it work?
public static void main(String[] args) { int a = 0; int b = 3; swap(a, b); } public static void swap (int x, int y){ int tmp = x; x = y; y = tmp; } Tell me please. How to make it work?
public static void main(String[] args) { int a = 0; int b = 3; swap(a, b); } public static void swap (int x, int y){ int tmp = x; x = y; y = tmp; } Primitives are not passed by reference. In your code, only local copies on the stack in the swap method change. Can be wrapped in something. Often do this:
public class IntRef { public int value; public IntRef (int val) { value = val; } } Then your code will be like this:
public static void main(String[] args) { IntRef a = new IntRef(0); IntRef b = new IntRef(3); swap(a,b); } public static void swap (IntRef x, IntRef y){ int tmp = x.value; x.value = y.value; y.value = tmp; } Integer in any way. And java.util.concurrent.atomic.AtomicInteger will help, since the mutable type ^^ - Suvitruf ♦There is no transfer of variables by reference in Java, so it is impossible to make a swap of two variables.
You can change the fields for objects, but it turns out that instead of two variables you need to have 2 fields (2 fields for one object, or 1 field for two objects), but this is clearly not something that you would have washed.
Source: https://ru.stackoverflow.com/questions/733556/
All Articles
swapmethod, which goes through the frogs in the lake. For a normal full-fledged question with a non-working code, it is always necessary to describe what it should do, what is wrong with it from your point of view and why (if any behavior is planned) should be like this - Alexey Shimansky