用于交换基元的Jave方法 [英] Jave method to swap primitives

查看:99
本文介绍了用于交换基元的Jave方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果没有可以通过引用传递的方法,如何在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 change wont be reflected back since java passes 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.

这篇关于用于交换基元的Jave方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆