问题描述
如果没有可以通过引用传递的方法,我该如何在 java 中创建我的交换函数?有人可以给我一个代码吗?
how do I make my swap function in java if there is no method by which we can pass by reference? Could somebody give me a code?
swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
但是由于java按值传递参数,因此更改不会反映回来.
But the changes wont be reflected back since java passes parameters by value.
推荐答案
你不能创建一个方法 swap,这样在调用 swap(x,y)
之后 x 和 y 的值会被交换.您可以通过交换它们的内容为可变类创建这样的方法¹,但这不会改变它们的对象标识,并且您无法为此定义通用方法.
You can't create a method swap, so that after calling swap(x,y)
the values of x and y will be swapped. You could create such a method for mutable classes by swapping their contents¹, but this would not change their object identity and you could not define a general method for this.
但是,如果需要,您可以编写一个方法来交换数组或列表中的两个项目.
You can however write a method that swaps two items in an array or list if that's what you want.
¹ 例如,您可以创建一个接受两个列表的交换方法,执行该方法后,列表 x 将拥有列表 y 的先前内容,而列表 y 将拥有列表 x 的先前内容.
¹ For example you could create a swap method that takes two lists and after executing the method, list x will have the previous contents of list y and list y will have the previous contents of list x.
这篇关于交换原语的Java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!