有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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);

}

共 (2) 个答案

  1. # 1 楼答案

    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. 一,

  2. # 2 楼答案

    类型java.lang.Integer表示一个永远不会改变其值的不可变的数。如果您想要一个可变的数字,请从Apache Commons中尝试MutableInt

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

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

    您可以使用List<T>编写类似的代码,但您总是需要一个(或两个)容器来交换东西