gpt4 book ai didi

java - 可以使用java中的包装类交换两个数字而不创建任何其他类吗?

转载 作者:行者123 更新时间:2023-11-30 01:57:46 26 4
gpt4 key购买 nike

这是我使用包装类交换两个数字的代码,我知道java只有值传递,所以我们不能使用像指针这样的东西来传递变量的地址。为此我创建了对象对于包装类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;
}

但我想知道我的方法到底出了什么问题。

最佳答案

不直接使用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);
}

得到相同的结果。

关于java - 可以使用java中的包装类交换两个数字而不创建任何其他类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53805826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com