Refer to some of the information on the Internet, and summarize it. You can go to the following bloggers for details
https://www.cnblogs.com/lixiaolun/p/4311863.html
http://blog.csdn.net/maoyeqiu/article/details/49250339
Here I find two ways to solve this problem:
The code of unchanged value is as follows:
package com.other.test;
public class Test {
public static void change(int i, int j) {
int temp = i;
i = j;
j = temp;
}
public static void main(String[] args) {
int a = 3;
int b = 4;
change(a, b);
System.out.println("a=" + a);
System.out.println("b=" + b);
}
}
The output result is a=3 b=4, and the transferred value does not change the original value
Method 1: (array)
package com.other.test;
public class Test {
public static void change(int[] counts) {
counts[0] = 6;
System.out.println(counts[0]);
}
public static void main(String[] args) {
int[] count = { 1, 2, 3, 4, 5 };
change(count);
System.out.println(count[0]);
}
}
The output is 6 6, which means the referenced value changes the original value
Method 2: (object)
package Test;
import java.util.Scanner;
class dataWrap
{
int a;
int b;
}
public class lsk{
public static void swap(dataWrap dw)
{
int tmp=dw.a;
dw.a=dw.b;
dw.b=tmp;
System.out.println("swap Method, the value of the member variable is"+dw.a+":b The value of the member variable is"+dw.b);
}
public static void main(String[] args)
{
dataWrap dw=new dataWrap();
dw.a=6;
dw.b=9;
swap(dw);
System.out.println("After transformation, a The value of the member variable is"+dw.a+":b The value of the member variable is:"+dw.b);
}
}
The operation result is:
In the swap method, the value of the member variable is 9:b the value of the member variable is 6
After transformation, the value of a member variable is 9:b member variable is 6
Method 2: Object-based can also be implemented in this way:
public class Test {
private static Integer a;
private static Integer b;
public void setA(Integer a) {
this.a = a;
}
public void setB(Integer b) {
this.b = b;
}
/* Exchange the values of two parameters in this method */
public void swap(Integer a, Integer b) {
setA(b);
setB(a);
}
public static void main(String[] args) {
a = new Integer(10);
b = new Integer(5);
System.out.println("a=" + a + "\tb=" + b);
new Test().swap(a, b);
System.out.println("a=" + a + "\tb=" + b);
}
}