Java:为什么这种交换方法不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2041542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:53:32  来源:igfitidea点击:

Java: Why does this swap method not work?

java

提问by witzar

I have the following code:

我有以下代码:

public class Main {

    static void swap (Integer x, Integer y) {
        Integer t = x;
        x = y;
        y = t;
    }

    public static void main(String[] args) {
       Integer a = 1;
       Integer b = 2;
       swap(a, b);
       System.out.println("a=" + a + " b=" + b);
    } 
}

I expect it to print a=2 b=1, but it prints the opposite. So obviously the swap method doesn't swap a and b values. Why?

我希望它打印 a=2 b=1,但它打印出相反的结果。所以很明显,swap 方法不会交换 a 和 b 值。为什么?

采纳答案by Svish

This doesn't have anything to do with immutability of integers; it has to do with the fact that Java is Pass-by-Value, Dammit!(Not annoyed, just the title of the article :p )

这与整数的不变性没有任何关系;它与Java 是按值传递的事实有关,该死!(不生气,只是文章的标题:p)

To sum up: You can't really make a swap method in Java. You just have to do the swap yourself, wherever you need it; which is just three lines of code anyways, so shouldn't be that much of a problem :)

总结一下:您无法真正在 Java 中创建交换方法。您只需要在任何需要的地方自己进行交换;反正这只是三行代码,所以应该不是什么大问题:)

    Thing tmp = a;
    a = b;
    b = tmp;

回答by Robert Christie

Integer are immutable - you can't change their values. The swapping that occurs inside the swap function is to the references, not the values.

整数是不可变的——你不能改变它们的值。交换函数内部发生的交换是引用,而不是值。

You would need to return both references in an array to achieve what you want

您需要在数组中返回两个引用才能实现您想要的

static Integer[] swap(Integer a, Integer b) {
   return new Integer[]{b, a};
}

public static void main(String[] args) {
   Integer a = 1;
   Integer b = 2;

   Integer[] intArray = swap(a, b);

   a = intArray[0];
   b = intArray[1];

   System.out.println("a=" + a + " b=" + b);
} 

IfInteger had a setValue method, you could do something like this.

如果Integer 有一个 setValue 方法,你可以做这样的事情。

static void swap(Integer a, Integer b) {
   int temp = a.intValue();
   a.setValue(b.intValue());
   b.setValue(temp);
}

But it doesn't - so to achieve what you want, return an array.

但它没有 - 所以要实现你想要的,返回一个数组。

回答by Ravi Gupta

Everything in Java is passed by value and the values of variables are always primitives or references to object.

Java 中的一切都是按值传递的,变量的值始终是原语或对对象的引用。

回答by ggf31416

You would need to pass the parameters by reference, which it's not possible in java. Also Integers are inmutables, so you cannot exchange the values as you don't have a setValue method.

您需要通过引用传递参数,这在 java 中是不可能的。整数也是不可变的,因此您无法交换值,因为您没有 setValue 方法。

回答by yawn

As Svish and others pointed out it it's call by value, not by reference in Java. Since you have no pointers in Java you need some kind of holder object to really swap values this way. For example:

正如 Svish 和其他人指出的那样,它是按值调用,而不是 Java 中的引用。由于您在 Java 中没有指针,因此您需要某种持有者对象来真正以这种方式交换值。例如:

static void swap(AtomicReference<Integer> a, AtomicReference<Integer> b) {

    Integer c = a.get();
    a.set(b.get());
    b.set(c);

}

public static void main(String[] args) {

    AtomicReference<Integer> a = new AtomicReference<Integer>(1);
    AtomicReference<Integer> b = new AtomicReference<Integer>(2);

    System.out.println("a = " + a);
    System.out.println("b = " + b);

    swap(a, b);

    System.out.println("a = " + a);
    System.out.println("b = " + b);

}

回答by Andreas Dolk

If you want to implement a swap method for Integer objects, you have to wrap the values into an array (or ArrayList) and swap inside the array. Here's an adaptation of your code:

如果要为 Integer 对象实现交换方法,则必须将值包装到数组(或 ArrayList)中并在数组内交换。这是您的代码的改编:

public class Main {

    static void swap (Integer[] values) {
        if ((values == null) || (values.length != 2)) {
          throw new IllegalArgumentException("Requires an array with exact two values");
        }

        Integer t = values[0];
        values[0] = values[1];
        values[1] = t;
    }

    public static void main(String[] args) {
       Integer a = 1;
       Integer b = 2;
       Integer[] integers= new Integer[]{a,b};
       swap(integers);
       System.out.println("a=" + integers[0] + " b=" + integers[1]);
    } 
}

(Just added this answer because Svish mentioned, that "You can't really make a swap method in Java"fg)

(刚刚添加了这个答案,因为 Svish 提到,“你不能真正在 Java 中创建一个交换方法” fg

回答by medopal

As all the guys mentioned its a Pass-By-Value thing.

正如所有这些人提到的那样,它是一个按值传递的东西。

Just liked to add: you can use this method of swapping GLOBAL integers.

只是想补充一点:您可以使用这种交换全局整数的方法。

private void swap (){
     a ^= b;
     b ^= a;
     a ^= b;
}

It eliminates the use of another variable, and its just cooler :)

它消除了另一个变量的使用,它只是更酷:)

回答by helpermethod

Using the XOR operator is a very bad idea:

使用 XOR 运算符是一个非常糟糕的主意:

First, it is far less readable. Second, there were times when this was faster but nowadays the opposite is the case. See

首先,它的可读性要差得多。其次,有时这会更快,但现在情况正好相反。看

Wikipedia

维基百科

for reference.

以供参考。

回答by Daniel Vaughn

Java code:

爪哇代码:

class swap {

    int n1;
    int n2;
    int n3;

    void valueSwap() {
        n3 = n1;
        n1 = n2;
        n2 = n3;
    }

    public static void main(String[] arguments) {

        Swap trial = new Swap();
        trial.n1 = 2;
        trial.n2 = 3;

        System.out.println("trial.n1 = " + trial.n1);
        System.out.println("trial.n2 = " + trial.n2);

        trial.valueSwap();

        System.out.println("trial.n1 = " + trial.n1);
        System.out.println("trial.n2 = " + trial.n2);

    }
}

Output:

输出:

trial.n1 = 2
trial.n2 = 3
trial.n1 = 3
trial.n2 = 2

回答by Siddhesh Urkude

Using Scanner:

使用扫描仪:

import java.util.*;
public class Swap {
 public static void main(String[] args){
  int i,temp,Num1,Num2;
  Scanner sc=new Scanner(System.in);
  System.out.println("Enter Number1 and Number2");
  Num1=sc.nextInt();
  Num2=sc.nextInt();
  System.out.println("Before Swapping Num1="+Num1+" Num2="+Num2);
  temp=Num1;
  Num1=Num2;
  Num2=temp;
  System.out.println("After Swapping Num1="+Num1+" Num2="+Num2);
 }    
}