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

可以在java中使用包装类交换两个数字而不创建任何其他类吗?,java,parameter-passing,pass-by-reference,wrapper,pass-by-value,Java,Parameter Passing,Pass By Reference,Wrapper,Pass By Value,这是我使用包装类交换两个数字的代码,我知道java只有传递值,所以我们不能使用指针之类的东西来传递变量的地址。为此,我为包装类整数a,b创建了对象。 但是这个代码不起作用,代码部分的注释解释了我的方法,有人能告诉我哪里出错了吗 class swp{ public static void main(String[] args) { Integer x = new Integer(5); //x --> obj with 5 int value Integer y = new Intege

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

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

不直接使用
整数
,但您可以使用
整数
(或
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按值传递引用<代码>整数是不可变的。所以不,你不能做你想做的事。尽管要注意两件事,
newinteger
永远不应该被调用,而且
Integer
[-128,128)
的值被缓存,所以
Integer x=5
将始终是
Integer
的同一个实例。您只是在移动本地指针。
swap
函数实际上什么都不做(据我所知)
java.lang.Integer
类是不可变的,因此除非您编写自己的包装器,否则您所要求的是不可能的。您为什么要这样做?好的,我明白了这一点,它与包装器类Integer本身的可模性有关。请帮助我理解这一点,并告诉我我是否错了。在“main”中,“x”和“y”仍然指向the相同的位置,但在“swap”函数中,我认为由“a”和“b”指向的位置的值已更改,而“a”和“b”现在指向一个完全不同的位置,该位置的值与“b.intvalue()”和“a.intvalue”相同