是否可以在 Java 中编写交换方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1363186/
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
Is it possible to write swap method in Java?
提问by AraK
Here is the question: write a method that swaps two variables. These two variables should be primitives. It doesn't need to be generic e.g. two int
variables. Is there a way?!
问题是:编写一个交换两个变量的方法。这两个变量应该是原语。它不需要是通用的,例如两个int
变量。有办法吗?!
采纳答案by Thomas Owens
Without using an array or objects, no, it is not possible to do it within a method.
不使用数组或对象,不,不可能在方法中执行此操作。
回答by Brent Writes Code
Check out this JavaWorld article that explains it in detail:
查看这篇 JavaWorld 文章,详细解释了它:
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
A swap of two primitives will never work because primitives are passed by value in Java. You can't even write a method to swap two objects for that matter.
两个原语的交换永远不会起作用,因为在 Java 中原语是按值传递的。你甚至不能写一个方法来交换两个对象。
Like @Thomas said, the only thing you could do is have your primitives contained within other objects/arrays and modify those.
就像@Thomas 所说的那样,你唯一能做的就是让你的原语包含在其他对象/数组中并修改它们。
回答by KLE
In java5, the closest I can think of, which may help you, is :
在java5中,我能想到的最接近的可能对你有帮助的是:
The AtomicInteger class (and others) have getAndSet()
atomic methods ..
AtomicInteger 类(和其他类)具有getAndSet()
原子方法..
回答by Chris Holland
As Thomas Owens said. You could probably do it in C by passing variables by &reference, but afaik not in Java without using objects.
正如托马斯·欧文斯所说。您可能可以通过通过 &reference 传递变量来在 C 中完成它,但是如果不使用对象,则不能在 Java 中完成。
回答by Michael Wiles
To write a swap method that swaps primitives you'd have to have the concept of "out" variables, i.e. variables whose values are passed up to the calling context. C# has those but you must still specify that they're out variables.
要编写交换原语的交换方法,您必须具有“输出”变量的概念,即其值向上传递到调用上下文的变量。C# 有这些,但您仍然必须指定它们是 out 变量。
回答by Victor
public class Swap
{
public static void main (String[]args)
{
int y = 5;
int x = 4;
int c;
System.out.println("y = "+y);
System.out.println("x = "+x);
c=x; //c = 4
x=y; //x = 5;
y=c;
System.out.println("\n");
System.out.println("y= "+y);
System.out.println("x= "+x);
}
}
回答by Fadi Hatem
This function will swap two ints
此函数将交换两个整数
Integer[] swap(int a, int b){
return new Integer[]{b,a};
}
回答by marcus
While it is not possible to write a function that simply swaps two variables, it is possible to write a helper functionthat allows you to:
虽然不可能编写一个简单地交换两个变量的函数,但可以编写一个辅助函数,使您能够:
- Swap two variables using only one statement
- Without temporary variablesin the caller's code
- Without 'boxing'primitives
- With a few overloads (one of them using generics), it works for any type
- 仅使用一条语句交换两个变量
- 在调用者的代码中没有临时变量
- 没有“拳击”原语
- 通过一些重载(其中一个使用泛型),它适用于任何类型
That's how you could do it:
这就是你可以做到的:
int returnFirst(int x, int y) {
return x;
}
int a = 8, b = 3;
a = returnFirst(b, b = a); // try reading this as a = b; b = a;
System.out.println("a: " + a + ", b: " + b); // prints a: 3, b: 8
This works because the Java language guarantees (Java Language Specification, Java SE 7 Edition, section 15.12.4.2) that all arguments are evaluated from left to right (unlike some other languages, where the order of evaluation is undefined), so the execution order is:
这是有效的,因为 Java 语言保证(Java 语言规范,Java SE 7 版,第 15.12.4.2 节)从左到右评估所有参数(与某些其他语言不同,评估顺序未定义),因此执行顺序是:
- The original value of
b
is evaluated in order to be passed as the first argument to the function - The expression
b = a
is evaluated, and the result (the new value ofb
) is passed as the second argument to the function - The function executes, returning the original value of
b
and ignoring its new value - You assign the result to
a
- 的原始值
b
被评估以便作为第一个参数传递给函数 - 计算表达式
b = a
,并将结果( 的新值b
)作为第二个参数传递给函数 - 函数执行,返回原始值
b
并忽略其新值 - 您将结果分配给
a
If returnFirst
is too long, you can choose a shorter name to make code more compact (e.g. a = sw(b, b = a)
). Use this to impress your friends and confuse your enemies :-)
如果returnFirst
太长,您可以选择一个较短的名称以使代码更紧凑(例如a = sw(b, b = a)
)。用它来打动你的朋友并迷惑你的敌人:-)
回答by dansalmo
You can make a generic version of @marcus's swap method that swaps any number of objects of the same type:
您可以制作@marcus 的 swap 方法的通用版本,用于交换任意数量的相同类型的对象:
<T> T swap(T... args) { // usage: z = swap(a, a=b, b=c, ... y=z);
return args[0];
}
b = swap(a, a=b);
z = swap(x, x=y, y=z);
回答by wonderer
Here's a method that swaps two primitive variables
这是一个交换两个原始变量的方法
private void swap(){
int a = 1;
int b = 2;
int temp = a;
a = b;
b = temp;
}
It might not be of much use though ;)
虽然它可能没有多大用处;)
Ok seriously, it could be done if the variables are class level:
好吧,如果变量是类级别的,就可以做到:
public class MyClass{
// excuse horrible coding practice of public mutable fields
public int a = 1;
public int b = 2;
public void swap(){
int temp = a;
a = b;
b = temp;
}
}
Again though, I fail to see what the use of this could be
再一次,我看不出这有什么用