交换原语的Java方法 [英] Java method to swap primitives
问题描述
如果没有可以通过引用传递的方法,我该如何在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(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方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!