Java严格超越价值!-IDC帮帮忙

考虑以下将原始类型传递给函数的Java程序。

public class Main
{
public static void main(String[] args)
{
int x = 5;
change(x);
System.out.println(x);
}
public static void change(int x)
{
x = 10;
}
}

输出:


我们将int传递给函数“change()”,因此该整数值的变化不会反映在main方法中。与C / C ++一样,Java创建了在方法中传递的变量的副本,然后进行操作。因此,改变不会反映在主要方法中。

对象或引用怎么样?

在Java中,所有基元(如int,char等)都与C / C ++类似,但所有非基元(或任何类的对象)始终是引用。因此,当我们将对象引用传递给方法时,它会变得棘手。Java创建引用的副本并将其传递给方法,但它们仍然指向相同的内存引用。意味着如果设置一些其他对象通过内部方法传递,则来自调用方法的对象及其引用将保持不受影响。
如果我们更改对象本身以引用其他位置或对象
,则不会反映更改如果我们将引用分配给其他位置,则更改不会反映在main()中。

// A Java program to show that references are also passed
// by value.
class Test
{
int x;
Test(int i) { x = i; }
Test() { x = 0; }
}

class Main
{
public static void main(String[] args)
{
// t is a reference
Test t = new Test(5);

// Reference is passed and a copy of reference
// is created in change()
change(t);

// Old value of t.x is printed
System.out.println(t.x);
}
public static void change(Test t)
{
// We changed reference to refer some other location
// now any changes made to reference are not reflected
// back in main
t = new Test();

t.x = 10;
}
}

输出:


如果我们不分配对新位置或对象的引用,则会反映更改:
如果我们不更改引用以引用其他对象(或内存位置),我们可以对成员进行更改,并反映这些更改。

// A Java program to show that we can change members using using
// reference if we do not change the reference itself.
class Test
{
int x;
Test(int i) { x = i; }
Test() { x = 0; }
}

class Main
{
public static void main(String[] args)
{
// t is a reference
Test t = new Test(5);

// Reference is passed and a copy of reference
// is created in change()
change(t);

// New value of x is printed
System.out.println(t.x);
}

// This change() doesn't change the reference, it only
// changes member of object referred by reference
public static void change(Test t)
{
t.x = 10;
}
}

输出:

10

练习:预测以下Java程序的输出

// Test.java
class Main {
// swap() doesn't swap i and j
public static void swap(Integer i, Integer j)
{
Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void main(String[] args)
{
Integer i = new Integer(10);
Integer j = new Integer(20);
swap(i, j);
System.out.println("i = " + i + ", j = " + j);
}
}