java 交换两个整数的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3901850/
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-10-30 03:54:46  来源:igfitidea点击:

Function that swaps two integers

java

提问by Armen Tsirunyan

Possible Duplicate:
How to write a basic swap function in Java

可能的重复:
如何用 Java 编写基本的交换函数

Hi. I don't know java at all, and in the near future have no wish to study it. However I have lots of friends that are java programmers and from conversations I learnt that there is no analog of C#'s ref keyword in Java. Which made me wonder how can one write a function that swaps two integers in Java. My friends (though not very good java experts) could not write such a function. Is it officially impossible? Please note, that I understand that one can swap two integers without a function, the question is exactly to write a function that takes two integers and swaps them. Thanks in advance.

你好。完全不懂java,近期也不想学。但是,我有很多 Java 程序员朋友,并且从对话中我了解到 Java 中没有类似于 C# 的 ref 关键字。这让我想知道如何在 Java 中编写一个交换两个整数的函数。我的朋友(虽然不是很好的java专家)写不出这样的函数。官方是不可能的吗?请注意,我知道一个人可以在没有函数的情况下交换两个整数,问题正是编写一个接受两个整数并交换它们的函数。提前致谢。

回答by Lie Ryan

Short: You can't.

简短:你不能。

Long: You need some workaround, like wrapping them in a mutable datatype, e.g. array, e.g.:

Long:您需要一些解决方法,例如将它们包装在可变数据类型中,例如数组,例如:

public static void swap(int[] a, int[] b) {
    int t = a[0]; a[0] = b[0]; b[0] = t;
}

but that doesn't have the same semantic, since what you're swapping is actually the array members, not the a and b themselves.

但这没有相同的语义,因为您交换的实际上是数组成员,而不是 a 和 b 本身。

回答by Kru

In Java, all the arguments are passed by value. So there is no such thing as a ref.

在 Java 中,所有参数都是按值传递的。所以没有ref.

However, you might achieve variable swapping by wapping values in objects (or arrays).

但是,您可以通过交换对象(或数组)中的值来实现变量交换。

public class Holder<T> {
  public T value = null;
  public Holder(T v) { this.value = v; }
}

public static <T> void swap(Holder<T> a, Holder<T> b) {
  T temp = a.value; a.value = b.value; b.value = temp;
}