参考了网上的一些资料,自己总结了一下,详细的可以去以下的博主看看
https://www.cnblogs.com/lixiaolun/p/4311863.html
http://blog.csdn.net/maoyeqiu/article/details/49250339
这里我搜到有两种方法解决这个问题:
不改变值得代码如下:
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);
}
}
输出的结果是 a=3 b=4,传递的值并不会改变原值
方法一:(数组)
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]);
}
}
输出结果是6 6 也就是引用的值改变了原来的值
方法二:(对象)
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方法里,成员变量的值是"+dw.a+":b成员变量的值是"+dw.b);
}
public static void main(String[] args)
{
dataWrap dw=new dataWrap();
dw.a=6;
dw.b=9;
swap(dw);
System.out.println("变换后,a成员变量的值是"+dw.a+":b成员变量的值为:"+dw.b);
}
}
运行结果为:
swap方法里,成员变量的值是9:b成员变量的值是6
变换后,a成员变量的值是9:b成员变量的值为:6
方法二基于对象的也可以这样子实现:
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;
}
/* 在此方法中实现交换两个参数的值 */
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);
}
}