下面是我使用包装类交换两个数字的代码,我知道java只有传递值,所以我们不能使用像指针这样的东西传递variables.For的地址--我为包装类Integer a,b创建了对象。
但是这段代码不起作用,代码部分的注释解释了我的方法,有人能告诉我哪里出错了吗?
class swp{
public static void main(String[] args) {
Integer x = new Integer(5); //x --> obj with 5 int value
Integer y = new Integer (6); //y --> obj with 6 int value
System.out.println("x = "+ x+ " " +"y = " + y);
swap(x,y);
System.out.println("x = " + x+ " " +"y = " + y);
}
//the values in x and y are copied in a and b
static void swap(Integer a,Integer b){ //a ,x--> obj with 5 int value .b,y --> obj with 6 int value
int temp = a.intValue(); // temp contains 5
a = b.intValue() ; // value at the obj ref. by a has changed to 6
b = temp; //value at the obj ref. by a has changed to 5
System.out.println("in func : "+"a = " + a+ " " +"b = " + b);
}
}输出
a = 5 b = 6
in func : a = 6 b = 5
a = 5 b = 6我知道我可以使用下面的方法来完成这个任务
void swap(class_name obj1,class_name obj2){
int temp = obj1.x;
obj1.x =obj2.x;
obj2.x = temp;
}但我想知道我的方法到底出了什么问题。
发布于 2018-12-16 19:50:42
不直接使用Integer,但可以使用Integer (或int)数组进行。喜欢,
public static void main(String[] args) {
int[] arr = { 5, 6 };
System.out.println("a = " + arr[0] + " " + "b = " + arr[1]);
swap(arr);
System.out.println("a = " + arr[0] + " " + "b = " + arr[1]);
}
private static void swap(int[] arr) {
int t = arr[0];
arr[0] = arr[1];
arr[1] = t;
}输出
a = 5 b = 6
a = 6 b = 5或创建一个POJO,
class MyPair {
private int a;
private int b;
public MyPair(int a, int b) {
this.a = a;
this.b = b;
}
public String toString() {
return String.format("a = %d, b = %d", a, b);
}
public void swap() {
int t = a;
a = b;
b = t;
}
}那你就可以
public static void main(String[] args) {
MyPair p = new MyPair(5, 6);
System.out.println(p);
p.swap();
System.out.println(p);
}同样的结果。
https://stackoverflow.com/questions/53805826
复制相似问题