是否可以在Java中交换两个变量? [英] Is it possible to swap two variables in Java?

查看:197
本文介绍了是否可以在Java中交换两个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

是否可以在Java中编写swap方法?

给定两个值x和y,我想将它们传递给另一个函数,交换它们的值并查看结果。这可能在Java中吗?

Given two values x and y, I want to pass them into another function, swap their value and view the result. Is this possible in Java?

推荐答案

不是原始类型( int long char 等)。 Java按值传递东西,这意味着你的函数传递的变量是原件的副本,你对副本所做的任何更改都不会影响原件。

Not with primitive types (int, long, char, etc). Java passes stuff by value, which means the variable your function gets passed is a copy of the original, and any changes you make to the copy won't affect the original.

void swap(int a, int b)
{
    int temp = a;
    a = b;
    b = temp;
    // a and b are copies of the original values.
    // The changes we made here won't be visible to the caller.
}

现在,对象有点不同,因为它的价值对象变量实际上是对对象的引用 - 复制引用使它指向完全相同的对象。

Now, objects are a bit different, in that the "value" of an object variable is actually a reference to an object -- and copying the reference makes it point at the exact same object.

class IntHolder { public int value = 0; }

void swap(IntHolder a, IntHolder b)
{
    // Although a and b are copies, they are copies *of a reference*.
    // That means they point at the same object as in the caller,
    // and changes made to the object will be visible in both places.
    int temp = a.value;
    a.value = b.value;
    b.value = temp;
}

限制是,您仍然无法修改<$ c $的值c> a 或 b 本身(也就是说,你不能将它们指向不同的对象)以调用者可以看到的任何方式。但是你可以交换他们引用的对象的内容。

Limitation being, you still can't modify the values of a or b themselves (that is, you can't point them at different objects) in any way that the caller can see. But you can swap the contents of the objects they refer to.

BTW,从OOP的角度来看,上面的内容相当可怕。这只是一个例子。不要这样做。

BTW, the above is rather hideous from an OOP perspective. It's just an example. Don't do it.

这篇关于是否可以在Java中交换两个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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