cHa*_*Hao 32
不与原始类型(int,long,char等).Java按值传递内容,这意味着函数传递的变量是原始副本,并且您对副本所做的任何更改都不会影响原始内容.
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.
}
Run Code Online (Sandbox Code Playgroud)
现在,对象有点不同,因为对象变量的"值"实际上是对对象的引用 - 复制引用使它指向完全相同的对象.
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;
}
Run Code Online (Sandbox Code Playgroud)
限制是,你仍然无法以调用者可以看到的任何方式修改a或b自己的值(也就是说,你不能将它们指向不同的对象).但是你可以交换它们引用的对象的内容.
顺便说一下,从OOP的角度来看,上述内容相当可怕.这只是一个例子.不要这样做.
因为"值"这个词在Java中有一个非常具体的含义,人们通常不会经常理解,尤其是当变量持有对象的引用时,我会在这里变得非常讨厌和迂腐.
我将假设问题要求这种行为:
x = initialValueForX;
y = initialValueForY;
swap(x, y);
// x now holds initialValueForY;
// y now holds initialValueForX;
Run Code Online (Sandbox Code Playgroud)
这是不可能的,因为Java会按值传递方法的所有参数.你永远无法改变存储内的实际值x和y这种方式.
你可以,但是,如果x和y持有对象的引用,改变这样的方式,使打印的值看起来像对方的初始值的两个对象的属性:
x = initialValueForX;
y = initialValueForY;
swap(x, y);
System.out.println(x); prints what looks like initialValueForY
System.out.println(y); prints what looks like initialValueForX
Run Code Online (Sandbox Code Playgroud)
如果你对价值的理解是对象的样子,而不是对象的身份,那么这就有效.通常,这是可以接受的.
(这将在这里给出一个很好的例子,但是cHao已经做了.还有其他人指出这无论如何都是一个重复的问题.)
| 归档时间: |
|
| 查看次数: |
88596 次 |
| 最近记录: |