Java 如何交换两个整数包装器对象

Java 如何交换两个整数包装器对象,java,reference,integer,Java,Reference,Integer,如何交换两个整数包装器的内容 void swap(Integer a,Integer b){ /*We can't use this as it will not reflect in calling program,and i know why Integer c = a; a= b; b = c; */ //how can i swap them ? Does Integer has some setValue kind of method? //

如何交换两个整数包装器的内容

void swap(Integer a,Integer b){
   /*We can't use this as it will not reflect in calling program,and i know why
    Integer c = a;
    a= b;
    b = c;
   */
  //how can i swap them ? Does Integer has some setValue kind of method?
  //if yes
    int c = a;
    a.setValue(b);
    b.setValue(c);

}

Java中的包装类型是不可变的,因此不提供setter方法。Plus Java通过按值传递引用来工作。你能告诉我们你为什么要交换东西吗?

请参阅本文以了解清楚


您将对“按值传递”和“按引用传递”及其概念有一个清晰的了解。您可以尝试以下方法:

class MyClass{
int a = 10 , b = 20;
public void swap(MyClass obj){
    int c;
    c = obj.a;
    obj.a = obj.b;
    obj.b = c;
}
public static void main(String a[]){
    MyClass obj = new MyClass();
    System.out.println("a : "+obj.a);
    System.out.println("b : "+obj.b);
    obj.swap(obj);
    System.out.println("new a : "+obj.a);
    System.out.println("new b : "+obj.b);
}
}
类型java.lang.Integer表示一个永远不会改变其值的不可变数字。如果您想要一个可变数字,请尝试Apache Commons中的可变整数

与C++相比,不能将引用传递给任意的内存位置,所以在大多数情况下交换是不可能的。你能得到的最接近的东西是:

public static void swap(Integer[] ints, int index1, int index2) {
  Integer tmp = ints[index1];
  ints[index1] = ints[index2];
  ints[index2] = tmp;
}

您可以使用列表编写类似的代码,但您始终需要一个或两个容器来交换内容。

您不能这样做,因为Integer和其他基本包装类型是不可变的。如果您有一个可变包装器类,则可以:

public final class MutableInteger {
{
    private int value;

    public MutableInteger(int value) {
        this.value = value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

void swap(MutableInteger a, MutableInteger b) {
    int c = a.getValue();
    a.setValue(b.getValue());
    b.setValue(c); 
}
然而,由于在Integer中缺少setValue的等价物,因此基本上没有办法满足您的要求。这是件好事。这意味着,在大多数情况下,我们可能希望将整数值传递给另一个方法,我们不需要担心该方法是否会对其进行变异。不变性使您更容易对代码进行推理,而无需仔细跟踪每个方法的作用,以防它更改您脚下的数据

public class NewInteger {
    private int a;
    private int b;

    public int getA() {
        return a;
    }

    public int getB() {
        return b;
    }

    public NewInteger(int a, int b) {
        this.a = a;
        this.b = b;
    }

    public void swap(){
        int c = this.a;
        this.a = this.b;
        this.b = c;
    }
}


NewInteger obj = new NewInteger(1, 2);
System.out.println(obj.getA());
System.out.println(obj.getB());
obj.swap();
System.out.println(obj.getA());
System.out.println(obj.getB());
输出: 1. 2. 2.
1

太糟糕了Stackoverflow没有检查帖子中的拼写。哦,等等,是的!你仍然设法发布一些几乎难以辨认的东西,这是一个相当了不起的壮举……因为人们在采访中会问这个问题:-